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;
    }

};

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/85267335
今日推荐