leetcode——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 thatk 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 or2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

解析:题目要求将字符串按规则解码。由于[]可能层层嵌套,因此可以使用递归的方式实现。定义返回字符串ss,对每个字符串,对于不在括号内的字符只需将其按顺序添加到ss中,若存在中括号,则只需找出每对第一层匹配中括号囊括的字串,并对该字串进行递归,将返回值添加到ss中即可。极端情况下算法复杂度为O(s.length^2),代码如下:

class Solution {
public:
	string decodeString(string s) {
		int n = s.length();
		string ss = "";
		for(int i=0; i= '0' && s[i] <= '9')
			{
				
				int j=i; 
				for(; j'9')
						break;
				int k = atoi(s.substr(i, j-i).c_str());
				stack sta;
				for(i=j; i


你可能感兴趣的:(leetcode——Decode String)