简体   繁体   English

Java 压缩没有回报?

[英]Java Compress no return?

what my code is supposed to be doing is converting input strings and outputing the compressed versions我的代码应该做的是转换输入字符串并输出压缩版本

Ex.前任。 Input: "qqqwww" Output: "3q3w".输入:“qqqwww” 输出:“3q3w”。

But my code returns nothing.但我的代码什么都不返回。

PS IO is just an input system. PS IO 只是一个输入系统。

public class Compress {
    public static String compress(String original){
        String s = "";

        char s1 = original.charAt(0);
        int count = 1;

        for(int i = 0; i < original.length(); i++){
            char c = original.charAt(i);

            if(c == s1){
                count++;
            }
            else{
                s = s + count + s1; //i think the problem is here right???
                count = 1;
            }
            s1 = c;
        }
        return s;

    }

    public static void main(String[] args){
        String s = IO.readString();

        String y = compress(s); 

        System.out.println(y);


    }

}

Your could should look like this :你可能应该是这样的:

String returnString="";
    for (int index = 0; index < original.length();) {
        char currentChar = original.charAt(index);
        int counter=1;
        while(++index < original.length() && currentChar==original.charAt(index)) {
            counter++;
        }
        returnString=returnString+counter+currentChar;
    }
    return returnString;
}

Here we loop thought the string (outer for loop) and check if the adjacent values are same the we keep adding them.在这里,我们循环考虑字符串(外部 for 循环)并检查相邻值是否相同,然后我们继续添加它们。 (inner while loop) (内部while循环)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM