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
or2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
思路:一看就知道要使用 栈 来做,给出的例子都是3种不同的例子,第一个例子左右各一对括号,第二个例子括号里面包含括号,第三个例子跟第一个例子差不多,但是还有尾巴。
代码附上:
class Solution {
public:
string decodeString(string s) {
stack<char> st;
int len = s.length();
string tmp;
string ret;
int i;
for(i=0;i<len;i++)
{
if(s[i]!=']')
st.push(s[i]);
else
{
while(st.top()!='[')
{
tmp.insert(tmp.begin(),st.top());
st.pop();
}
st.pop(); // pop '['
int reapt = st.top()-'0';
string tmp_tmp = tmp;
for(int i=0;i<reapt-1;i++)
tmp+=tmp_tmp;
st.pop(); // pop '3'
if(st.empty())
{
ret+=tmp;
tmp="";
}
}
}
if(i==len && !st.empty())
{
string ttt;
while(!st.empty())
{
ttt.insert(ttt.begin(),st.top());
st.pop();
}
ret += ttt;
}
return ret;
}
};
提交以为会AC,结果很令人变态。。。也是我写程序没有考虑到的情况,数字连续有好几位的情况:100[abcd]. 令人崩溃了,下次来修这个bug!