394. Decode String
来源:互联网 发布:天刀捏详细步骤脸数据 编辑:程序博客网 时间:2024/06/01 22:40
这道题目要实现的是字符串按照输入的格式进行解码,有点类似RLE算法,但是更复杂一点,因为这里有嵌套的解码,主要做法如下:
1、利用stack的先入后出性,设置countstack和resstack分别存储数字和字符;
2、当遇见‘【’时候,先把res放入resstack中,再reset为“”,来存储下次的字符
3、当遇见‘】’时候,先把resstack中pop,再加上下次要重复的字符(pop countstack 数字作为重复次数)。
代码如下:
public static String decodeString(String s) { String res=""; Stack<Integer> countStack=new Stack<>(); Stack<String> resStack=new Stack<>(); int index=0; while (index<s.length()) { int count=0; if (Character.isDigit(s.charAt(index))) { while (Character.isDigit(s.charAt(index))) { count=10*count+(s.charAt(index)-'0'); index++; } countStack.push(count); } else if (s.charAt(index)=='[') { resStack.push(res); res=""; index++; } else if (s.charAt(index)==']') { StringBuffer sb=new StringBuffer(resStack.pop()); int num=countStack.pop(); for (int i = 0; i < num; i++) { sb.append(res); } res=sb.toString(); index++; } else { res +=s.charAt(index); index++; } } return res; }
0 0
- 【Leetcode】394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 【leetcode】394. Decode String
- 394. Decode String
- leetcode ----394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- 394. Decode String
- [leetcode] 394. Decode String
- [Leetcode]394. Decode String
- 394. Decode String
- 【LeetCode】 394. Decode String
- 394. Decode String
- LeetCode 394. Decode String
- Leetcode 394. Decode String
- 用CTime类得到当前日期、时间、星期,并格式化输出
- 【HUD 1262】寻找素数对
- 使用nginx配置nodejs服务进行反向代理
- J2SE习题—基础语法1
- 数据结构与算法 -- 算法
- 394. Decode String
- 进程基础知识思维导图
- 信息奥赛 约瑟夫环问题
- 345. Reverse Vowels of a String
- Java对象的序列化和反序列化及其实现和使用
- 有关Android活动——写给自己看
- 顺序结构、动态链表结构下的一元多项式的加法、减法等的实现
- 【redis】redis的bind配置
- JSP内容整理之JavaBeans与JSP动作元素