#LeetCode
题目描述
初次解法
class Solution {
public String compressString(String S) {
if("".equals(S)) return S;
int pre = 0;
int letter_numbers = 1;
int set_numbers = 1;
int sum = 0;
StringBuilder sb = new StringBuilder();
sb.append(S.charAt(0));
for(int last = 1; last < S.length(); last++){
if(S.charAt(last) != S.charAt(pre)){
sb.append(letter_numbers);
sb.append(S.charAt(last));
set_numbers++;
sum = sum + letter_numbers;
letter_numbers = 1;
}else{
letter_numbers ++;
}
pre++;
}
sum += letter_numbers;
sb.append(letter_numbers);
if(sum > 2 * set_numbers) return new String(sb);
else return S;
}
}
优化解法
- 去除无用变量,直接用长度比较。
- 想复杂了
class Solution {
public String compressString(String S) {
if("".equals(S)) return S;
int pre = 0;
int letter_numbers = 1;
StringBuilder sb = new StringBuilder();
sb.append(S.charAt(0));
for(int last = 1; last < S.length(); last++){
if(S.charAt(last) != S.charAt(pre)){
sb.append(letter_numbers);
sb.append(S.charAt(last));
letter_numbers = 1;
}else{
letter_numbers ++;
}
pre++;
}
sb.append(letter_numbers);
String ans = new String(sb);
return S.length() > ans.length() ? ans : S;
}
}
三次优化(别人)
- 双指针定位与跳转,优化时间
class Solution {
public String compressString(String S) {
if("".equals(S)) return S;
int len = S.length();
int i = 0;
StringBuilder sb = new StringBuilder();
while(i < len){
int j = i;
while(j < len && S.charAt(i) == S.charAt(j)){
j++;
}
sb.append(S.charAt(i));
sb.append(j-i);
i = j;
}
String ans = new String(sb);
return S.length() > ans.length() ? ans : S;
}
}