[programming questions] basic string compression

  • 热度: 58188 time limit: 3 seconds space limit: 32768K

use the number of repeated characters, write a The method implements basic string compression. For example, the string "aabcccccaaa" will become "a2b1c5a3" after compression. If the compressed string is not shortened, the original string is returned.

Given a string iniString for the string to be compressed (length less than or equal to 10000), ensure that the characters in the string are composed of uppercase and lowercase English letters, and return a string, which is the compressed or unchanged string.

测试样样

"aabcccccaaa"
返回:"a2b1c5a3"
"welcometonowcoderrrrr"
返回:"welcometonowcoderrrrr"

码代码:

import java.util.*;

public class Zipper {
    public String zipString(String iniString) {
        // write code here
        if (iniString == null || iniString.trim().length() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        char[] iniStr = iniString.toCharArray();
        char pre = iniStr[0];
        int count = 1;
        for(int i = 1; i < iniStr.length; i++)
        {
            if(iniStr[i] == pre)
            {
                count++;
            }
            else
            {
                sb.append(pre + "" + count);
                count = 1;
                pre = iniStr[i];
            }
        }
        sb.append(pre + "" + count);
        if(sb.toString().length() >= iniString.length())
        {
            return iniString;
        }
        return sb.toString();
    }
}