394. 字符串解码https://leetcode.cn/problems/decode-string/
难度中等1281
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string]
,表示其中方括号内部的 encoded_string
正好重复 k
次。注意 k
保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k
,例如不会出现像 3a
或 2[4]
的输入。
示例 1:
输入:s = "3[a]2[bc]" 输出:"aaabcbc"
示例 2:
输入:s = "3[a2[c]]" 输出:"accaccacc"
示例 3:
输入:s = "2[abc]3[cd]ef" 输出:"abcabccdcdcdef"
示例 4:
输入:s = "abc3[cd]xyz" 输出:"abccdcdcdxyz"
提示:
1 <= s.length <= 30
s
由小写英文字母、数字和方括号'[]'
组成s
保证是一个 有效 的输入。s
中所有整数的取值范围为[1, 300]
通过次数197,890提交次数349,540
class Solution {
public String decodeString(String s) {
// 遍历s:遇到数字入栈 遇到字母入栈
// 遇到 ] : 出栈:(若出栈元素一直为字母,则字母相加起来)直到遇到数字,碰到数字后相加起来的字母做乘法,存入栈中,继续遍历
// 创建栈:
Stack<String> stack = new Stack<>();
int x =0;
String str = "";
String ans = "";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='[')
{
continue;
}
else if(s.charAt(i)>='0' && s.charAt(i)<='9')
{
while(i<s.length() && s.charAt(i)>='0' && s.charAt(i)<='9')
{
int z = s.charAt(i)-'0';
x = x*10+z;
i++;
}
i--;
if(x!=0) stack.push(x+"");
x=0;
}
else if(s.charAt(i)>='a' && s.charAt(i)<='z')
{
int j = i;
while(i<s.length() && s.charAt(i)>='a' && s.charAt(i)<='z')
{
i++;
}
if(i==j) str = s.charAt(i)+"";
else str = s.substring(j,i);
i--;
stack.push(str);
str="";
}
else if(s.charAt(i)==']' || i==s.length()-1) //出栈
{
String ss = "";
String s1 = "";
while(!(stack.peek().charAt(0)>='0' && stack.peek().charAt(0)<='9')) //取到的不是数字
{
ss = stack.pop()+ss;
}
int o = Integer.parseInt(stack.pop());
while(o>=1){
s1 += ss;
o--;
}
stack.push(s1);
}
}
for (String e : stack) ans+=e;
return ans;
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧
相关推荐
暂无评论内容