Expression Expand---lintcode
来源:互联网 发布:淘宝超级运动会 编辑:程序博客网 时间:2024/06/07 11:50
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.
Examples
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
我开始做的时候 想利用map<string,integer>
将[]里的字母 和前面的数字保存在map里。可是,写着写着。。突然想起来 map的key是不可以相同的。这个想法放弃。
之后利用stack.保存。然后遇到各种顺序错乱。。然后修改修再修改。。中间省略3小时。还是不行 ,没办法 百度。。于是就找到了这篇:网址https://segmentfault.com/a/1190000008883991。他说的几个坑 我全遇到了。
代码如下:
public class Solution { /** * @param s an expression includes numbers, letters and brackets * @return a string */ public String expressionExpand(String s) { // Write your code here Stack<Object> stack = new Stack<>(); char[] arr = s.toCharArray(); int num = 0; for(char c : arr){ if(Character.isDigit(c)){ //如果数字是 多位的 ,如23. //开始num=0,所以执行后num=2.因为23是连起来的 //所以num=2*10+3=23.最后num=23 num = num * 10 + c - '0'; } else if(c == '['){ stack.push(Integer.valueOf(num)); num = 0; } else if(c == ']'){ popStack(stack); } else{ stack.push(c); } } popStack(stack); return stack.pop().toString(); } private void popStack(Stack<Object> stack){ StringBuilder add = new StringBuilder(); int count; Stack<Object> buffer = new Stack<Object>(); while(!stack.isEmpty() && stack.peek() instanceof Integer == false){ buffer.push(stack.pop()); } while(!buffer.isEmpty()){ add.append(buffer.pop()); } //下面例子里xyz.那时stack是空的。所以只需要一次就行 count = stack.isEmpty()? 1 : (Integer) stack.pop(); StringBuilder part = new StringBuilder(add); if(count > 0){ for(int i = 0; i < count - 1; i++) add.append(part); stack.push(add); } }}
这里我以s="3[2[ad]3[pf]]xyz"
为例说明一下:
遇到’]’将stack里 数字之前的字母 pop给buffer.然后赋值给add.根据数字 来append字符串。
阅读全文
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
- 在Github和Git上fork之简单指南
- UNIX环境高级编程——第五章-标准I/O库
- lua if语句不跟elseif 需要end
- 【day-15】golang各种排序
- Html常用标签元素
- Expression Expand---lintcode
- 一起艳学正则表达式
- Ueditor开发实例
- 全志R16平台的androidM下调通AP6330(V2.1系统)(分色排版)
- 第四章——栈与队列
- Notepad++里面正则表达式反向引用和替换的一个例子
- Java基础学习总结(三)—— 面向对象特征(封装|继承|多态)
- 利用SpringAOP技术完成数据库连接事物实战
- 【leetcode】3.Longest Substring Without Repeating Characters