Leetcode算法學習日誌-394 Decode String

Leetcode 394 Decode String

題目原文

Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

題意分析

方括號前的數字代表方括號中string需要重複的次數,解碼就是將所有string按照數字表示的次數展開。

解法分析

本題方括號中又嵌套有方括號,就想到從內到外展開,運用遞歸的思想,本題的關鍵在於定義一個全局變量i,用來記錄已經遍歷到的s的位置。本題另一個關鍵是數字可能是多位的。C++代碼如下:

class Solution {
private:
    int i;//globle variable
    string S;
public:
    string recursion(){
        string cur,count;
        for(;i<S.size();i++){
            if(S[i]==']')
                break;
            if(isdigit(S[i]))
                count.push_back(S[i]);
            else if(S[i]=='['){
                i++;
                string temp=recursion();
                for(int j=0;j<stoi(count);j++)
                    cur+=temp;
                count="";
            }
            else
                cur.push_back(S[i]);
        }
        return cur;  
    }
    string decodeString(string s) {
        S=s;
        i=0;
        return recursion();
      
      } 
};
對於字符,可以用isdigit()來判斷是否是數字字符。上述代碼中,如果遇到【便進入遞歸調用,i同時加一,如果遇到】就返回,因此遞歸的返回條件是多樣的,要根據問題來定。

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