我的字符串压缩 for 循环有点偏离。在过去的 5 天里,我一直在处理这项任务,但我终究无法弄清楚哪里出了问题。有人可以帮帮我吗?
例如,我传递了字符串 "TTTTrrrREe"
,我得到的不是 T4r3Ee
,而是 T4r3EeTT
。我不知道为什么它会那样跳回到字符串的开头,但我越来越接近了。我们只能使用 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;
}
最佳答案
由于这是一个学习练习,我不会尝试修复您的代码,只是指出一些需要改进的地方:
if (i !=s.length()-1)
如果您更改for
,则循环内的条件变得不必要循环条件为i < s.length()-1
- 比较单个字符比比较子字符串更容易(也更快)。您在位置
i
处得到一个字符调用char ch1 = s.charAt(i)
, 并使用==
比较两个字符运算符(operator),而不是调用equals()
在他们身上。 - 何时
count
为零(您的count < 1
条件相当于count == 0
)除了temp
的第一个字符外,您还打印当前字符及其后的字符其次是伯爵。这看起来不正确。 - 而不是增长
temp
当你通过循环时,你在每次迭代中设置它。这看起来不正确。 - 更好的成长方式
temp
当你通过循环时使用StringBuilder
和append()
,而不是使用普通的String
,并执行连接。
关于java - 字符串压缩循环逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742610/