[LintCode] String Compression

1468 ワード

String Compression
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
If the "compressed"string would not become smaller than the original string, your method should return the original string.
You can assume the string has only upper and lower case letters (a-z).
Example
str=aabcccccaaa return a2b1c5a3str=aabbcc return aabbccstr=aaaa return a4
Solution
public class Solution {
    /*
     * @param str: a string
     * @return: a compressed string
     */
    public String compress(String str) {
        if (str == null || str.length() < 3) {
            return str;
        }
        StringBuilder sb = new StringBuilder();
        Map map = new HashMap<>();
        char pre = str.charAt(0);
        map.put(pre, 1);
        for (int i = 1; i < str.length(); i++) {
            char cur = str.charAt(i);
            if (cur == pre) {
                map.put(pre, map.get(pre)+1);
            } else {
                sb.append(pre);
                sb.append(map.get(pre));
                map.put(pre, 0);
                map.put(cur, 1);
                pre = cur;
            }
        }
        sb.append(pre);
        sb.append(map.get(pre));
        String res = sb.toString();
        return res.length() < str.length() ? res : str;
    }
}