首页 > 学院 > 开发设计 > 正文

Decode string----字符串解码问题

2019-11-10 17:53:58
字体:
来源:转载
供稿:网友

问题描述

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

自己写的程序:

#include<iostream>#include<string>#include<unordered_map>using namespace std;class Solution {public: string decodeString(string s) { string s2; int k1=0; int k2=0; int k3=0; int i=0; int num; while (i < s.size()) { num = 0; int j = i; while (s[j]!='['&&j<s.size()) { num = num * 10 + s[j] - '0'; j++; } k2 = j+1; while(s[j]!=']'&&j<s.size()) { j++; } k3 = j-1; while(num>0) { for (int i = k2;i <=k3;i++) s2.push_back(s[i]); num--; } i = j+1; } return s2; }};void main(){ Solution s; string a = "3[a]2[b]"; cout << s.decodeString(a) << endl;}

注:只针对没有嵌套的字符串序列,在写程序的时候j=i++,和j=i+1有很大的不一样

参考的程序 class Solution { public: string decodeString(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 decodeString(s, i);}

};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表