使用重复字符计数执行基本基本字符串压缩的方法

时间:2015-12-12 04:49:20

标签: java

//除了以下之外还有其他实施方式吗?请建议

color:#FFF

6 个答案:

答案 0 :(得分:0)

您的代码至少有两个默认值:

  • 大一点:你混合了char和nimbers。然后,如果你存储,例如:x11,你如何区别于xxxxxxxxxxx,......

  • 你没有编码解码部分。你会遇到上一点的问题

建议:使用一些“escape”字符来表示count:like / 11 /,如果你想编码/,只需使用//

解码起来会更容易。

希望有所帮助

答案 1 :(得分:0)

有一种更好的方法。您可以使用Java Collections中的HashSet容器。 HashSet是一个使用Hashing的容器,允许在分摊的 O(1)时间内查找和插入条目。

在您的方案中,您可以将每个字符(如果HashSet中不存在)插入集合中,同时将其附加到StringBuilder对象。最后,将其转换为String,您就完成了。

String a="aaaabbbbcccc";
StringBuilder sb=new StringBuilder();
HashSet<Character> hs=new HashSet<Character>(); //Stores a unique entry for each character
for(int i=0;i<a.length();i++)
    if(!hs.contains(a.charAt(i)))
    {
        sb.append(a.charAt(i));
        hs.add(a.charAt(i));
    }
String compStr=sb.toString();
System.out.println(compStr);

答案 2 :(得分:0)

这是一个非常简单的解决方案,不使用Java中的任何集合。 在这种方法中,将字符与下一个位置字符进行比较,并为字符串&amp;中出现的每个字符取一个名为count = 1的变量。在重复的情况下,我们将增加这个数量。经过比较,我们有两种可能性: 1.如果比赛然后继续增加1。 2.如果有匹配,则打印当前字符和计数。 这是代码。

class CompressionString {
public static void main(String[] args) {
    String str = "aabcccccaaa";
   // for each character present in the string
    int count = 1;
    for (int i = 0; i < str.length(); i++) {
        //comparing char to next position character
        if (i < str.length() - 1) {
            if (str.charAt(i) == str.charAt(i + 1)) {
                count++;
            }
            //if char doesn't match then print character and total count
            else {
                System.out.print(str.charAt(i) + "" + count);
                count = 1;
            }
        }
        //this condition for the last character
        else {
            System.out.println(str.charAt(i) + "" + count);
        }
    }

}

}

答案 3 :(得分:0)

我使用过C#-我们可以使用StringBuilder类来附加字符及其计数。

使用for循环遍历。

编写一个IF条件,以将字符及其相应的计数附加到StringBuilder中。

最后,检查压缩字符串的长度是否小于源字符串。如果是,则返回压缩的字符串作为输出。

    public static string CompressedString(string source)
    {
        int countConsecutive = 0;
        string compressed = String.Empty;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < source.Length; i++)
        {
            countConsecutive++;
            if (i >= source.Length - 1 || source[i] != source[i + 1])
            {
                sb.Append(source[i]);
                sb.Append(countConsecutive);
                countConsecutive = 0;
            }
        }

        compressed = sb.ToString();
        Console.WriteLine($"Compressed String is {compressed}");
        return (compressed.Length < source.Length) ? compressed : source;
    }

答案 4 :(得分:0)

下面是相同问题的Python实现,以防万一。更加简洁明了。

遍历所需的字符串,同时跟踪上次访问的字符,并在下一个字符等于上一个字符时增加计数。如果下一个字符不同,则将当前字符及其计数添加到列表(compressed_str)中并重置计数器。

由于循环将在到达字符串末尾后结束,因此要处理最后一个char压缩,必须将其计数保存在循环主体之外的列表中。

列表将用于将字符及其出现的次数保存在字符串中,并最终进行连接以生成最终的压缩字符串。

例如,给定字符串“ aabbbcaa”的对应列表将为[a,2,b,3,c,1,a,2]

s = 'aabbbcaa'
last_seen_char = ''
count = ''

if s:
    last_seen_char = s[0]
    count = 1

compressed_str = []

for i in range(1, len(s)):
    if s[i] == last_seen_char:
        count += 1
    else:
        compressed_str.extend([last_seen_char, str(count)])
        last_seen_char = s[i]
        count = 1

compressed_str.extend([last_seen_char, str(count)])

compressed_str = ''.join(compressed_str)

print(compressed_str)

# a2b3c1a2 is your compressed string

答案 5 :(得分:0)

python实现。

def stringComprehension(string):
    compressedString = ""
    consecutiveStringCount = 1

    if len(string) < 2:
        return string

    for i in range(len(string)-1):
        if string[i] == string[i + 1]:
            consecutiveStringCount += 1
        else:
            compressedString += string[i] + str(consecutiveStringCount)
            consecutiveStringCount = 1
    compressedString += string[i+1] + str(consecutiveStringCount)

    if len(compressedString) >= len(string):
        return string
    else:
        return compressedString


def test():
    input1 = "tTTttaAbBBBccDd"
    input2 = "aabcccccaaa"
    input3 = "abcd"
    input4 = "aaaaaabbccbcaabb"
    input5 = "aabcccccaa"
    input6 = "a"

    print(input1, "compressed string -->", stringComprehension(input1))
    print(input2, "compressed string -->", stringComprehension(input2))
    print(input3, "compressed string -->", stringComprehension(input3))
    print(input4, "compressed string -->", stringComprehension(input4))
    print(input5, "compressed string -->", stringComprehension(input5))
    print(input6, "compressed string -->", stringComprehension(input6))


test()