天天看點

[leetcode/lintcode 題解] 阿裡面試真題詳解:字元串壓縮

描述

設計一種方法,通過給重複字元計數來進行基本的字元串壓縮。

例如,字元串 aabcccccaaa 可壓縮為 a2b1c5a3 。而如果壓縮後的字元數不小于原始的字元數,則傳回原始的字元串。

可以假設字元串僅包括 a-z 的大/小寫字母。

線上評測位址:

領扣題庫官網

樣例1
Input: str = "aabcccccaaa"
Output: "a2b1c5a3"           
樣例2
Input: str = "aabbcc"
Output: "aabbcc"           

源代碼

public class Solution {
    /**
     * @param str a string
     * @return a compressed string
     */
    public String compress(String str) {
        // Write your code here
        /* Check if compression would create a longer string */
        int size = countCompression(str);
        if (size >= str.length()) {
            return str;
        }

        char[] array = new char[size];
        int index = 0;
        char last = str.charAt(0);
        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == last) { // Found repeated character
                count++;
            } else {
                /* Update the repeated character count */
                index = setChar(array, last, index, count);
                last = str.charAt(i);
                count = 1;
            }
        }
        /* Update string with the last set of repeated characters. */
        index = setChar(array, last, index, count);
        return String.valueOf(array);
    }

    public int setChar(char[] array, char c, int index, int count) {
        array[index] = c;
        index++;
        char[] cnt = String.valueOf(count).toCharArray();

        /* Copy characters from biggest digit to smallest */
        for (char x : cnt) {
            array[index] = x;
            index++;
        }
        return index;
    }

    int countCompression(String str) {
        if (str == null || str.isEmpty()) return 0;
        char last = str.charAt(0);
        int size = 0;
        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == last) {
                count++;
            } else {
                last = str.charAt(i);
                size += 1 + String.valueOf(count).length();
                count = 1;
            }
        }
        size += 1 + String.valueOf(count).length();
        return size;
    }
}           

更多題解參考:

九章官網solution

繼續閱讀