Sunday, July 7, 2019

LeetCode [394] Decode String

Given an encoded string, return its 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".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
    stack<int> stkk;
    stack<string> stks;
public:
    string decodeString(string s) {
        string cur;//inner-most string
        int n = s.size(), i = 0;
        while(i<n){
            char c = s[i];
            if(isdigit(c)){
                int k = 0;
                while(i<n && isdigit(s[i])){k = k*10+(s[i++]-'0');}
                stkk.push(k);
            }else if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
                i++;
                cur += c;
            }else if(c=='['){
                i++;
                stks.push(cur);
                cur = "";
            }else{//']'
                i++;
                int cnt = stkk.top();
                stkk.pop();
                string prev = stks.top();
                stks.pop();
                for(int j=0; j<cnt; ++j) prev+=cur;
                cur = prev;
            }
        }
        return cur;
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Java
class Solution {
    public String decodeString(String s) {
        int i = 0, n = s.length();
        Stack<String> stkW = new Stack<>();
        Stack<Integer> stkI = new Stack<>();
        int k = 0;
        StringBuilder w = new StringBuilder();
        while (i < n) {
            if (Character.isDigit(s.charAt(i))) {
                while (i < n && Character.isDigit(s.charAt(i))) {
                    k = k * 10 + (s.charAt(i++) - '0');
                }
                stkI.add(k);
                k = 0;
            } else if (Character.isAlphabetic(s.charAt(i))) {
                w.append(s.charAt(i++));
            } else if (s.charAt(i) == '[') {
                stkW.push(w.toString());
                w.setLength(0);
                i++;
            } else {//']'
                i++;
                int l = stkI.pop();
                String cur = w.toString();
                w = new StringBuilder(stkW.pop());
                for(int j=0; j<l; ++j){
                    w.append(cur);
                }
            }
        }
        return w.toString();
    }
}

No comments:

Post a Comment