DecodeString 解析字符串
题目描述
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].
示例
s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.
题目解析
给一个编号的字符串,返回他的解码字符串。
从题中我们可以看出,当碰到括号时。需要将括号内的字符串根据括号前的数字来复制字符串。我们可以把题目解析成这样,没遇到一个括号就计算一次字符串,也就是解码一次字符串,然后将其与前面的字符串结合进行下一次解码。由于每次都要与前面的字符串结合,这里必须记录一个状态下的前面字符串。因此我们可以用栈的方式来记录栈的状态以及字符串。由题目知道,我们需要记录的由两个状态,一个是字符串,一个是需要重复的次数。因此设计了两个栈来记录中间状态。
得到如下代码。
代码解析
/**
* @author AbrahamHan
* @param s
* @return res
*/
public String decodeString(String s) {
int len = s.length();
//数字栈,记录每层数字大小
LinkedList<Integer> numstack = new LinkedList<Integer>();
//String栈,记录每层String
LinkedList<String> strstack = new LinkedList<String>();
String res = "",tmp="",str = "";
Integer num = 0;
for(int i = 0 ; i < len ; i++){
char ch = s.charAt(i);
if(ch == ']')
{
num = numstack.pop();
//如果匹配到后括号,直接计算当前栈的字符串
String tmpstr = "";
for(int j = 0;j < num ;j++)
tmpstr = tmpstr + str;
str = strstack.pop() +tmpstr;
num = 0;
}
//如果匹配到左括号,将当前栈的数字和str压入栈
else if(ch == '[')
{
numstack.push(num);
strstack.push(str);
str = "";
num = 0;
}
//如果匹配到数字,计算数值大小
else if(ch>='0' && ch <= '9')
{
num = num * 10 + (ch-'0');
}
//如果匹配到字符,计算字符串
else
{
str = str +ch;
}
}
return str;
}