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 ...
随机推荐
- POJ 3281 Dining ( 最大流 && 建图 )
题意 : 有 N 头牛,John 可以制作 F 种食物和 D 种饮料, 然后接下来有 N 行,每行代表一头牛的喜好==>开头两个数 Fi 和 Di 表示这头牛喜欢 Fi 种食物, Di 种饮料 ...
- 07-图5 Saving James Bond - Hard Version (30 分)
This time let us consider the situation in the movie "Live and Let Die" in which James Bon ...
- vue 之 nextTick 与$nextTick
VUE中Vue.nextTick()和this.$nextTick()怎么使用? 官方文档是这样解释的: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 D ...
- Jupyter 环境配置
1. 找到python文件目录, 用管理员身份打开powershell python -m pip install jupyter 2. Jupyter notebook
- cpp中memset函数的注意点
可参考: C++中memset函数的用法 C++中memset函数的用法 C++中memset()函数的用法详解 c/c++学习系列之memset()函数 透彻分析C/C++中memset函数 mem ...
- 3d Max 2010安装失败怎样卸载3dsmax?错误提示某些产品无法安装
AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...
- webview的进度条的加载,webview的使用以及handle的理解与使用
Webview的几个关键方法要介绍一些: 谷歌官方文档是这么说的; A WebView has several customization points where you can add your ...
- Kudu的架构
不多说,直接上干货! Kudu的架构 1.kudu的 基本框架 Kudu 是用于存储结构化( structured )的表( Table ).表有预定义的带类型的列( Columns ),每张表有一 ...
- BoostrapTable-本地模式(一次性加在所有数据)
直接上代码 数据: [ { "id": "1001", "name": "yyq", "isAdmin&quo ...
- 【linux】Linux tcpdump命令详解
Tcpdump 用简单的话来定义tcpdump,就是:dump the traffic on a network,根据使用者的定义对网络上的数据包进行截获的包分析工具. tcpdump可以将网络中传送 ...