您的位置:首页 > 其它

Decode String_Week10

2017-11-12 22:14 344 查看

Decode String_Week10

题目:(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”.

难度: Medium

解题思路:

题意由Examples可轻松得知。

我的思路为:

①遍历string s,用两个vector:coeff 和 braket 分别记录系数,和左括号 [ 的数组下标。 (即以压栈的形式记录)

②当遇到右括号 ] 时,就出栈最后一个左括号 [,取出系数和左括号的下标。

③用一个临时变量substring存储要替换的子字符串,即3[a]变成substring = aaa

④最后用substring = aaa 把”3[a”这一段替换掉。即若原string s = 3[a]2[bc],则第一次替换后,s = aaa2[bc];若原string s = 2[bc3[a]], 则第一次替换后,s = 2[bcaaa]。

⑤因为string已被替换,长度改变,内容改变,所以将i重置为-1,重新从s[0]开始循环,直至s中没有[]

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;

class Solution {
public:
string decodeString(string s) {
//coeff用于压栈系数,bracket用于压栈左括号[的下标,即s中第几个字符
vector<int> coeff, bracket;
int frontBracket, backBracket;
//用于将string中的系数转换成int数字
int tempNum = 0;
for (int i = 0; i < s.size(); i++) {
//当遇到左括号[时,将前面计算出的系数压栈,并存储左括号[在string s中的下标
if (s[i] == '[') {
coeff.push_back(tempNum);
bracket.push_back(i);
tempNum = 0;
} else if (s[i] == ']') {
//当遇到右括号],即可开始替换子字符串
string substring = "";
frontBracket = bracket.back();
bracket.pop_back();
backBracket = i;
int coe = coeff.back();
coeff.pop_back();
//利用系数循环将3[a]变为aaa
for (int j = 0; j < coe; j++) {
substring += s.substr(frontBracket+1,backBracket-frontBracket-1);
}
int coeDigit = getDigit(coe);
//将“3[a]”这一整个子串替换为 aaa
s.replace((frontBracket-coeDigit),(backBracket-frontBracket+coeDigit+1),substring);
//因string s已被替换,长度内容发生变化,重置i,从头开始遍历string s
i = -1;
} else if (s[i] >= '0' && s[i] <= '9'){
//将string中的数字一位一位转换为int
tempNum = tempNum * 10 + s[i] - '0';
}
}
return s;
}

private:
//计算系数的位数,如100为2位数,用于计算替代子串时应替代的长度
int getDigit(int a) {
int digit = 0;
while(a) {
a /= 10;
digit++;
}
return digit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: