字符串壓縮(遞歸回調,內存消耗(比較耗時)最少的方法(內存擊敗100%))

image.png

本題採用遞歸回調整合新字符串方式處理
首先要注意一點:若“壓縮”後的字符串沒有變短,則返回原先的字符串
這句話可以直接理解成當新生成字符串<=2或着新生成字符串>=原始字符串,直接輸出原始字符串即可

class Solution {
    public int count = 1, index = 0;
    public String newStr = "";
    public String compressString(String s) {
        // 當字符串長度小於2的時候直接返回字符串就行
        if (s.length() <= 2 ) {
            return s;
        }
        if ((index + 1) >= s.length()) {
            newStr += s.charAt(index);
            newStr += count;
            // 將長度判斷放在這裏是爲了確保新生成的完整字符串的長度大於原始字符串
            if (newStr.length() >= s.length()) {
                return s;
            }
            return newStr;
        }
        if (s.charAt(index) != s.charAt(index + 1)) {
            newStr += s.charAt(index);
            newStr += count;
            count = 1;
            index++;
            return compressString(s);
        } else {
            count++;
            index++;
            return compressString(s);
        }   
    }
}

Leetcode鏈接:

https://leetcode-cn.com/problems/compress-string-lcci/solution/di-gui-hui-diao-nei-cun-xiao-hao-bi-jiao-hao-shi-z/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章