小编Bob*_*lou的帖子

字符串压缩循环逻辑

我的for循环为我的字符串压缩有点偏.过去5天我一直在做这项任务,我无法弄清楚我的生活有什么不对.有人可以帮我吗?

例如,我通过了字符串"TTTTrrrEe",而不是得到T4r3Ee,我得到了T4r3EeTT.我不知道为什么它跳回这样的字符串的开头,但我正在逐渐closer.We只能用charAt,equals,length,并substring从字符串类.

有人可以通过帮助纠正我的逻辑来帮助指导我朝着正确的方向前进吗?我仍然想尝试自己编写代码,看看它是如何分配的.

public static String compress(String s){
    int count = 0;
    String temp = s.substring(0,1);
    for(int i = 0; i < s.length(); i++){
        if(i !=s.length()-1){
            if(temp.equals(s.substring(i,i+1))){
                count++;

            }else{

                if(count < 1){
                    System.out.print(s.substring(i,i+2));
                    System.out.print(temp.substring(0,1) );
                }else{
                    System.out.print("" + temp.substring(0,1) + count);
                    i--;
                    temp = s.substring(count,count+1);
                    System.out.println(" temp is now " + temp);

                    count = 0;
                    //i--;
                }
            }
        }

    }

    System.out.println(temp);

    return temp;
}
Run Code Online (Sandbox Code Playgroud)

java compression string

5
推荐指数
1
解决办法
783
查看次数

标签 统计

compression ×1

java ×1

string ×1