1. 程式人生 > >Decode String(394)

Decode String(394)

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”.

C++程式碼:

class Solution {
public:
    string decodeString(string s) {
      vector<int> vec_times;
      vector<string> vec_result;
      string result="";
      int i = 0;

      while(i < s.length()){
        if(s[i] == '[') {   //"[]”之前的入棧
          vec_result.push_back(result)
; result = ""; i++; } else if(isalpha(s[i])){ result += s[i]; i++; } else if(isdigit(s[i])) { int times = 0; while(isdigit(s[i])){ times = times *10 +(s[i]-'0'); i++; } vec_times.push_back(times); }else if(s[i] == ']'){ //遇到“]”,說明“[]”之前的串要與“[]”之中的相加 string tmp = vec_result.back(); vec_result.pop_back(); int times = vec_times.back(); vec_times.pop_back(); for(int i = 0; i< times; i++){ tmp = tmp + result; } result = tmp; i++; } } return result; } };

Complexity Analysis:

Time complexity : O( n n ).
Space complexity : O( n n ).

思路1:

  • 每次遇到“[” 時,意味著需要將前面的串儲存, 與“[]”裡面k倍後的結果連線
  • 每次遇到“]” 時,“[]”內部串完成, 可以與前面串進行連線
  • 用棧儲存“[]”前面的串,

思路2:

  • 遞迴的思想
  • 每次遞迴返回“[]” 的結果
  • 每次遞迴的出口條件是: 遇到“]”或遍歷字串長度

C++程式碼:

class Solution {
public:
    string decodeString(string s) {
      int i = 0;
      return helper(s,i);
    }

    string helper(string s, int &i){
      string result = "";
      while(i < s.length() && s[i] != ']'){
        if(isalpha(s[i])){
          result += s[i];
          i++;
        } else {
          int times = 0;
          while(i < s.length() && isdigit(s[i])) {
            times = times *10 + (s[i]-'0');
            i++;
          }
          i++; // 數字後面一定是“[”,跳過,進入下一層遞迴
          string tmp = helper(s,i);     //返回“[]”裡面的結果
          i++; // “]”
          while(times-- > 0) {
            result += tmp;
          }
        }
      }
      return result;
    }

};