本题采用递归回调整合新字符串方式处理
首先要注意一点:若“压缩”后的字符串没有变短,则返回原先的字符串。
这句话可以直接理解成当新生成字符串<=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链接: