clueless coding // TODO: be smarter

LeetCode 394. Decode String: C++ Solution



Problem Statement


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 can 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].

Function Signature (C++):
  string decodeString(string s)

Inputs:
  s = "3[a]2[bc]"

Outputs:
  "aaabcbc"

Inputs:
  s = "2[abc]3[cd]ef"

Outputs:
  "abcabccdcdcdef"



TL;DR Code Solution


string decodeStringHelper(const string& s, int& i) {

    string res;

    while (i < s.length() && s[i] != ']') {
        if (!isdigit(s[i]))
            res += s[i++];
        else {
            int n = 0;
            while (i < s.length() && isdigit(s[i]))
                n = n * 10 + s[i++] - '0';

            i++; // '['
            string t = decodeString(s, i);
            i++; // ']'

            while (n-- > 0)
                res += t;
        }
    }

    return res;

}

string decodeString(string s) {
    int i = 0;
    return decodeStringHelper(s, i);
}