[英]Java Compress no return?
我的代碼應該做的是轉換輸入字符串並輸出壓縮版本
前任。 輸入:“qqqwww” 輸出:“3q3w”。
但我的代碼什么都不返回。
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);
}
}
你可能應該是這樣的:
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;
}
在這里,我們循環考慮字符串(外部 for 循環)並檢查相鄰值是否相同,然后我們繼續添加它們。 (內部while循環)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.