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.

  1. stack里面装的一直是“还没配好对的括号的index”
  2. 是’(‘的时候push
  3. 是’)‘的时候,说明可能配对了;看stack top是不是左括号,不是的话,push当前右括号
  4. 是的话,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:栈的更多相关文章

  1. Leetcode栈&队列

    Leetcode栈&队列 232.用栈实现队列 题干: 思路: 栈是FILO,队列是FIFO,所以如果要用栈实现队列,目的就是要栈实现一个FIFO的特性. 具体实现方法可以理解为,准备两个栈, ...

  2. leetcode 栈 括号匹配

    https://oj.leetcode.com/problems/valid-parentheses/ 遇到左括号入栈,遇到右括号出栈找匹配,为空或不匹配为空, public class Soluti ...

  3. leetcode 栈和队列类型题

    1,Valid Parentheses bool isVaild1(string& s) { // 直接列举,不易扩展 stack<char> stk; ; i < s.le ...

  4. 【Leetcode栈】有效的括号(20)

    题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 1,左括号必须用相同类型的右括号闭合. 2,左括号必须以正确的顺序闭合. 注意 ...

  5. [LeetCode] Implement Queue using Stacks 用栈来实现队列

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  6. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  7. [LeetCode] Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  8. LeetCode之Min Stack 实现最小栈

    LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: ...

  9. leetcode Maximal Rectangle 单调栈

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052721.html 题目链接:leetcode Maximal Rectangle 单调栈 ...

  10. leetcode Largest Rectangle in Histogram 单调栈

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052343.html 题目链接 leetcode Largest Rectangle in ...

随机推荐

  1. HDU2665(可持久化线段树板子)

    1.题意有坑,实际要求第k小. 2.没学过动态开点也没学过主席树,看一下博主思路然后妄想自己实现的后果就是拿命去调bug. const int maxn = 1e5 + 5; int test, n, ...

  2. 求js数组的最大值和最小值

    数组 ,,,,,,,,,]; 方法1 - 字符串拼接法 利用toString或join把数组转换为字符串,再和Math的max和min方法分别进行拼接,最后执行eval方法 var max = eva ...

  3. Android 选择本地图片的demo

    https://github.com/lipanquan/SelectLocalPhoto

  4. python基础之1--Python入门

    第1章 Python生态圈 第2章 编程与编程语言 python是一门编程语言,作为学习python的开始,需要事先搞明白:编程的目的是什么?什么是编程语言?什么是编程? 2.1 编程的目的: 计算机 ...

  5. build-helper-maven-plugin

    <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven ...

  6. AdvancedEncryptionStandard

    import java.security.GeneralSecurityException; import javax.crypto.Cipher; import javax.crypto.spec. ...

  7. 测试用例逐步演进-xmind2excel(Python版)测试用例逐步演进-xmind2excel(Python版)

    最近,我在做项目的时候,经常被问到一个问题:如何做测试评审会更有效呢? 只要做过测试用例评审,特别是比较复杂的测试用例评审的时候,很多测试同学都会苦恼于如何能更有效的向大家说出自己的测试设计思路. 当 ...

  8. B树与B+

    简单剖析B树(B-Tree)与B+树https://blog.csdn.net/z_ryan/article/details/79685072 B树和B+树的插入.删除图文详解https://www. ...

  9. Python数据可视化--matplotlib

    抽象化|具体化: 如盒形图 | 现实中的图 功能性|装饰性:没有装饰和渲染 | 包含艺术性美学上的装饰 深度表达|浅度表达:深入层次的研究探索数据 | 易于理解的,直观的表示 多维度|单一维度:数据的 ...

  10. java多线程(四)

    一个例子: Account.java 客户实体类 package com.asiainfo.test.thread8; /** * 账户类 * @author luke * */ public cla ...