題目
通過鍵盤輸入一串小寫字母(a~z)組成的字符串。請編寫一個字符串壓縮程序,將字符串中連續出席的重複字母進行壓縮,並輸出壓縮後的字符串。
壓縮規則:
- 僅壓縮連續重複出現的字符。比如字符串abcbc由於無連續重複字符,壓縮後的字符串還是abcbc
- 壓縮字段的格式爲"字符重複的次數+字符"。例如:字符串xxxyyyyyyz壓縮後就成爲3x6yz
- 你可以假設字符串中只包含大小寫英文字母(a至z)。
代碼
package compress_string_lcci;
class Solution {
//自己寫的代碼
public String compressString(String S) {
if (S == null || "".equals(S))
return S;
char[] cc = S.toCharArray();
int len = cc.length;
char t = cc[0];
int num = 1;
StringBuffer buff = new StringBuffer();
for (int i = 1; i < len; i++) {
if (t == cc[i]) {
num++;
} else {
buff.append(t).append(num);
t = cc[i];
num = 1;
}
}
buff.append(t).append(num);
String nstr = buff.toString();
if (len <= nstr.length()) {
return S;
}
return nstr;
}
//官方代碼
public String compressString2(String S) {
if ((int)S.length() == 0) return S; // 空串處理
String ans = "";
int cnt = 1;
char[] arr = S.toCharArray();
char ch = arr[0];
for (int i = 1; i < (int)S.length(); ++i){
if (ch == arr[i]) cnt++;
else{
ans += ch + cnt; // 注意 cnt 要轉爲字符串
ch = arr[i];
cnt = 1;
}
}
ans += ch + cnt;
return ans.length() >= S.length() ? S : ans;
}
public static void main(String[] args) {
String ss1 = "aabcccccaaa";
String ss2 = "abbccd";
String ss3 = "bb";
Solution solu = new Solution();
System.out.println(solu.compressString(ss1));
System.out.println(solu.compressString(ss2));
System.out.println(solu.compressString(ss3));
}
}