问题描述
给定一个拥有固定格式的字符串n[s],将其解析成ss…s(重复n次)的形式。
解法分析
这题涉及到符号匹配,可以考虑使用栈这一FILO的数据结构来帮助解决问题。因为数字必定表示倍数,不会是转换后的字符串的内容,所以遍历字符串遇到数字时,将其转换成整数形式存在int栈内;若是读到字母,将其存入缓存字符串;“[”符号意味着重复字符串的开始,这里可以将前面已经读到的内容先存入strnig栈内;“]”符号意味着重复字符串的结束,这时从int栈顶pop出其重复次数,执行repeat操作后将其与string栈顶的已读内容合并到缓存字符串。顺序遍历过原字符串后,依据上述操作进行处理,最后将缓存字符串返回出来即可。
代码实现
class Solution {
public:
string decodeString(string s) {
string rtn = "";
stack<int> cnt;
stack<string> tmp;
int index = 0;
while (index < s.size()) {
if (s[index] == '[') {
tmp.push(rtn);
rtn = "";
index++;
} else if (s[index] == ']') {
string temp = rtn;
rtn = tmp.top();
tmp.pop();
for (int i = cnt.top(); i > 0; i--) {
rtn += temp;
}
cnt.pop();
index++;
} else if (isdigit(s[index])) {
int multi = 0;
while (isdigit(s[index])) multi = multi*10 + s[index++]-'0';
cnt.push(multi);
} else {
rtn += s[index++];
}
}
return rtn;
}
};
这道题主要考察栈的操作,想让代码更加优雅的话可以采用递归函数的形式,不过本质上并无太大区别就是了。