leetcode:栈
1. evaluate-reverse-polish-notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 用一个栈存储操作数,遇到操作数直接压入栈内,遇到操作符就把栈顶的两个操作数拿出来运算一下,然后把运算结果放入栈内。
public class Solution {
public int evalRPN(String[] tokens) {
int ret = 0;
Stack<Integer> num = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
if (isOperator(tokens[i])) {
int b = num.pop();
int a = num.pop();
num.push(calc(a, b, tokens[i]));
} else {
num.push(Integer.valueOf(tokens[i]));
}
}
ret = num.pop();
return ret;
}
boolean isOperator(String str) {
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"))
return true;
return false;
}
int calc(int a, int b, String operator) {
char op = operator.charAt(0);
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
}
2. Longest Valid Parentheses
Given a string containing just the characters ‘(‘ and ‘)‘, find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
给定一个字符串值包含字符‘(‘ and ‘)‘,找出最长有效括号子串。
对于 "(()",最长有效子串为"()",长度为2.
另一个例子是")()())",其中的最长有效括号子串为"()()",长度为4.
- stack里面装的一直是“还没配好对的括号的index”
- 是’(‘的时候push
- 是’)‘的时候,说明可能配对了;看stack top是不是左括号,不是的话,push当前右括号
- 是的话,pop那个配对的左括号,然后update res:i和top的(最后一个配不成对的)index相减,就是i属于的这一段的当前最长。如果一pop就整个栈空了,说明前面全配好对了,那res就是最大=i+1
public class Solution
{
public int longestValidParentheses(String s)
{
int res = 0;
Stack<Integer> stack = new Stack<Integer>();
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++)
{ //Pop()取出栈顶元素,栈顶元素被弹出Stack;
//Peek()读得栈顶元素,但栈顶元素没有被弹出Stack。
if (arr[i] == ')' && !stack.isEmpty() && arr[stack.peek()] == '(')
{
stack.pop();
if (stack.isEmpty())
res = i + 1;
else
res = Math.max(res, i - stack.peek());
}
else
{
stack.push(i);
}
}
return res;
}
}
3. vali parentheses
Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid.
The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are not.
一个个检查给的characters,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。
全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
注意:
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。
public boolean isValid(String s) {
if(s.length()==0||s.length()==1)
return false;
Stack<Character> x = new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
x.push(s.charAt(i));
}else{
if(x.size()==0)
return false;
char top = x.pop();
if(s.charAt(i)==')')
if(top!='(')
return false;
else if(s.charAt(i)=='}')
if(top!='{')
return false;
else if(s.charAt(i)==']')
if(top!='[')
return false;
}
}
return x.size()==0;
}
leetcode:栈的更多相关文章
- Leetcode栈&队列
Leetcode栈&队列 232.用栈实现队列 题干: 思路: 栈是FILO,队列是FIFO,所以如果要用栈实现队列,目的就是要栈实现一个FIFO的特性. 具体实现方法可以理解为,准备两个栈, ...
- leetcode 栈 括号匹配
https://oj.leetcode.com/problems/valid-parentheses/ 遇到左括号入栈,遇到右括号出栈找匹配,为空或不匹配为空, public class Soluti ...
- leetcode 栈和队列类型题
1,Valid Parentheses bool isVaild1(string& s) { // 直接列举,不易扩展 stack<char> stk; ; i < s.le ...
- 【Leetcode栈】有效的括号(20)
题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 1,左括号必须用相同类型的右括号闭合. 2,左括号必须以正确的顺序闭合. 注意 ...
- [LeetCode] Implement Queue using Stacks 用栈来实现队列
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...
- [LeetCode] Implement Stack using Queues 用队列来实现栈
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- [LeetCode] Min Stack 最小栈
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- LeetCode之Min Stack 实现最小栈
LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: ...
- leetcode Maximal Rectangle 单调栈
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052721.html 题目链接:leetcode Maximal Rectangle 单调栈 ...
- leetcode Largest Rectangle in Histogram 单调栈
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052343.html 题目链接 leetcode Largest Rectangle in ...
随机推荐
- 南昌大学航天杯第二届程序设计竞赛校赛网络同步赛 I
链接:https://www.nowcoder.com/acm/contest/122/I来源:牛客网 题目描述 小q最近在做一个项目,其中涉及到了一个计时器的使用,但是笨笨的小q却犯难了,他想请你帮 ...
- Experimental Educational Round: VolBIT Formulas Blitz N
Description The Department of economic development of IT City created a model of city development ti ...
- keepalived企业管理
实践案例一:更改nginx反向代理只监听vip地址 10.0.0.3/nana.html 可以使用 10.0.0.5/nana.html 不可以使用 10.0.0.6/nana.html 不可以使 ...
- Python中的sin和cos函数
1 第一次使用math.sin()和math.cos(),可是发现结果不对,比如Math.sin(90)=0.893996663600,奇怪? 2 3 一查,原来sin(x) \n\n Ret ...
- 在Mac上配置iTerm2+Oh-My-Zsh&配置主题
本教程基本完全按照iTerm2 + Oh My Zsh 打造舒适终端体验配置 但是个人感觉博主的颜色搭配不合理,体现在补全命令的字体不清晰,提示命令与背景颜色太过相近 所以,再此之后使用了Bullet ...
- java多线程 栅栏CyclicBarrier
CyclicBarrier类介绍A synchronization aid that allows a set of threads to all wait for each other to rea ...
- maya2012无法安装卸载激活失败
AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...
- Unity 组件.name
组件.name 指的是组件所在游戏对象的名字,例如: Animation m_animation; m_animation =GetComponent<Animation>(); m_a ...
- mysql连接查看
1:查看当前连接 mysql> show status like 'Threads%'; +-------------------+-------+ | Variable_name | ...
- 工作采坑札记:1. Hadoop中的BytesWritable误区
1. 背景 近日帮外部门的同事处理一个小需求,就是将HDFS中2018年至今所有存储的sequence序列化文件读取出来,重新保存成文本格式,以便于他后续进行处理.由于同事主要做机器学习方向,对had ...