利用字元重複出現的次數,編寫一個方法,實作基本的字元串壓縮功能。比如,字元串“aabcccccaaa”經壓縮會變成“a2b1c5a3”。若壓縮後的字元串沒有變短,則傳回原先的字元串。
給定一個string iniString為待壓縮的串(長度小于等于10000),保證串内字元均由大小寫英文字母組成,傳回一個string,為所求的壓縮後或未變化的串。
測試樣例
“aabcccccaaa”
傳回:”a2b1c5a3”
“welcometonowcoderrrrr”
傳回:”welcometonowcoderrrrr”
解題思路:定義一個StringBuilder,周遊字元串,停機是否有重複出現的字元,有的話則累加,每個字元後面跟上對應字元的個數,與原字元串長度進行比較,短則采用,否則,不采用。
import java.util.*;
public class Zipper {
public String zipString(String iniString) {
// write code here
int low = , high = ;
int len = iniString.length();
StringBuilder sb = new StringBuilder();
char c = ' ';
int count = ;
while(low < len){
high = low;
c = iniString.charAt(low);
while((high < len)&&(iniString.charAt(high) == c)){
high ++;
}
count = high - low ;
sb.append(c);
sb.append(count);
low = high;
}
return (sb.toString().length() < len)?sb.toString():iniString;
}
}