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 n).
Space complexity : O( n 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;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值