Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在基本压缩算法中额外计算一个字符_Java_Algorithm - Fatal编程技术网

Java 在基本压缩算法中额外计算一个字符

Java 在基本压缩算法中额外计算一个字符,java,algorithm,Java,Algorithm,我正在根据破解代码访谈版本5中的问题构建一个基本的压缩算法: 实现一种方法,使用 重复的字符。例如,字符串aabcccaaa将变为 a2blc5a3。如果“压缩”字符串不小于原始字符串 字符串,则方法应返回原始字符串 这是我的算法: public static String compress(String str) { StringBuffer comp = new StringBuffer(); int count = 1; char currentChar = st

我正在根据破解代码访谈版本5中的问题构建一个基本的压缩算法:

实现一种方法,使用 重复的字符。例如,字符串aabcccaaa将变为 a2blc5a3。如果“压缩”字符串不小于原始字符串 字符串,则方法应返回原始字符串

这是我的算法:

public static String compress(String str) {
    StringBuffer comp = new StringBuffer();
    int count = 1;

    char currentChar = str.charAt(0);
    for(int i = 0; i < str.length(); i++) {
        if(currentChar == str.charAt(i)) {
            count++;
        } else {
            comp.append(currentChar);
            comp.append(count);
            count = 1;
            currentChar = str.charAt(i);
            System.out.println(currentChar);
        }
    }

    comp.append(currentChar);
    comp.append(count);

    return comp.toString();
}
我得到以下输出:

b
c
d
e
f
a4b1c1d1e1f1
具体而言,
a
被额外计算一次。为什么会这样?

改变这个

     for(int i = 0; i < str.length(); i++)

因此,您希望从字符串中的第二个字符开始。

您还可以更改
int count=1到<代码>整数计数=0

那会解决你的问题

问题在for循环中:

for(int i = 0; i < str.length(); i++)

您的字符串甚至更为压缩且仍然无损:

a4bcdef

哦!这就是为什么。谢谢。别忘了检查
str.length()。如果要使用单字符的运行长度,如果它们是二进制的,而不是字符串,那么效率会更高。因此,范围将是1-255(或1-65535),而不是1-9。解码将跳过字符串到int步。实际上,1-127可以避免UTF8带来的麻烦,在Java的UTF16中,您必须避免创建两个字符的起始代理项对字符。
    char currentChar = str.charAt(0);
for(int i = 0; i < str.length(); i++)
for(int i = 1; i < str.length(); i++)
comp.append(count);
comp.append(count==1?"":count);
a4bcdef