1. 程式人生 > >基本字串壓縮Java實現

基本字串壓縮Java實現

利用字元重複出現的次數,編寫一個方法,實現基本的字串壓縮功能。比如,字串“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 = 0 , high = 0 ;
        int len = iniString.length();
        StringBuilder sb = new StringBuilder();
        char c = ' ';
        int count = 0;
        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; } }