本題採用遞歸回調整合新字符串方式處理
首先要注意一點:若“壓縮”後的字符串沒有變短,則返回原先的字符串。
這句話可以直接理解成當新生成字符串<=2或着新生成字符串>=原始字符串,直接輸出原始字符串即可
class Solution {
public int count = 1, index = 0;
public String newStr = "";
public String compressString(String s) {
// 當字符串長度小於2的時候直接返回字符串就行
if (s.length() <= 2 ) {
return s;
}
if ((index + 1) >= s.length()) {
newStr += s.charAt(index);
newStr += count;
// 將長度判斷放在這裏是爲了確保新生成的完整字符串的長度大於原始字符串
if (newStr.length() >= s.length()) {
return s;
}
return newStr;
}
if (s.charAt(index) != s.charAt(index + 1)) {
newStr += s.charAt(index);
newStr += count;
count = 1;
index++;
return compressString(s);
} else {
count++;
index++;
return compressString(s);
}
}
}
Leetcode鏈接: