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".
Solution 1: Recursion
Time complexity: O(n^2)
Space complexity: O(n)
C++
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 35 36 37 38 39 40 |
// Author: Huahua, 4ms class Solution { public: string decodeString(string s) { if (s.empty()) return ""; string ans; int i = 0; int n = s.length(); int c = 0; while (isdigit(s[i]) && i < n) c = c * 10 + (s[i++] - '0'); int j = i; if (i < n && s[i] == '[') { int open = 1; while (++j < n && open) { if (s[j] == '[') ++open; if (s[j] == ']') --open; } } else { while (j < n && isalpha(s[j])) ++j; } // "def2[ac]" => "def" + decodeString("2[ac]") // | | // i j if (i == 0) return s.substr(0, j) + decodeString(s.substr(j)); // "3[a2[c]]ef", ss = decodeString("a2[c]") = "acc" // | | // i j string ss = decodeString(s.substr(i + 1, j - i - 2)); while (c--) ans += ss; // "3[a2[c]]ef", ans = "abcabcabc", ans += decodeString("ef") ans += decodeString(s.substr(j)); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment