lintcode(575)Expression Expand
来源:互联网 发布:西南大学远程网络培训 编辑:程序博客网 时间:2024/06/07 19:04
Description:
Given an expression s
includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.
Explanation:
s = abc3[a]
return abcaaa
s = 3[abc]
return abcabcabc
s = 4[ac]dy
, return acacacacdy
s = 3[2[ad]3[pf]]xyz
, return adadpfpfpfadadpfpfpfadadpfpfpfxyz
Challenge:
Can you do it without recursion?
Solution:
Reverse traversal. 倒序遍历字符串,如果遇到‘]’, count(层数)+1,将之后的字符串添加到list[count]中,直到遇到‘[’,然后计算重复次数,按照次数执行复制后,将结果添加到list的上一层中。最后list[0]即为结果。主要添加字符时,要添加到前面(倒序遍历)。
public class Solution { /** * @param s an expression includes numbers, letters and brackets * @return a string */ public String expressionExpand(String s) { // Write your code here int index = s.length() - 1; ArrayList<String> res = new ArrayList<String>(); res.add(""); int count = 0; while(index >= 0){ if(s.charAt(index) == ']'){ res.add(""); count++; index--; } else if(s.charAt(index) == '['){ index--; int time = 0; String t = ""; while(index >= 0 && s.charAt(index) - '0' >= 0 && s.charAt(index) - '0' <= 9){ t = s.charAt(index) + t; index--; } for(int j = 0;j<t.length();j++){ time = time*10 + (t.charAt(j) - '0'); } for(int i = 0;i<time;i++){ res.set(count - 1 , res.get(count) + res.get(count - 1) ); } res.set(count , ""); count--; } else { res.set(count , s.charAt(index) + res.get(count)); index--; } } return res.get(0); }}
阅读全文
0 0
- lintcode(575)Expression Expand
- lintcode--Expression Expand
- 【LintCode】Expression Expand
- Expression Expand---lintcode
- LintCode:M-Expression Expand
- LintCode-分治-Expression Expand
- lintcode :expression expand using C++
- Expression Expand
- Expression Expand
- Expression Expand
- Expression Expand
- Lintcode - Expression Evaluation
- Lintcode - Expression Evaluation
- [LintCode] Expression Evaluation
- Lintcode - Convert Expression to Reverse Polish Notation
- Lintcode - Convert Expression to Polish Notation
- [LintCode] Convert Expression to Polish Notation
- [LintCode]Convert Expression to Reverse Polish Notation
- 单循环链表的创建、插入删除等操作
- Unity 与 NGUI 坐标转换原理
- POJ 3087 Shuffle'm Up 模拟
- php错误级别设置
- JAVA——网络编程(3):Java编写在TCP网络连接上传递对象
- lintcode(575)Expression Expand
- Libxml2交叉编译
- Linux 开发过程中I/O操作的效率测试
- LBP(局部二值模式)特征提取原理
- 561. Array Partition I
- python学习笔记(四)XML解析
- 用golang编写一个并发工作队列
- git切换分支
- python:并行化网格搜索中ImportError: [joblib] Attempting to do parallel computing without protecting...