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. Educational Codeforces Round 3 C

    C. Load Balancing time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  2. 浅谈dedecms模板引擎工作原理及其自定义标签

    浅谈dedecms模板引擎工作原理: 理解织梦模板引擎有什么意思? 可以更好地自定义标签.更多在于了解织梦系统,理解模板引擎是理解织梦工作原理的第一步. 理解织梦会使我们写PHP代码是更顺手,同时能学 ...

  3. linux学习3(vim)

    一.文档编辑 1. vi和vim命令 Vim的打开文件的方式(4种,要求掌握的就前三种): 1. vim 文件路径                                            ...

  4. redis 集合

    > SADD myset1 a b c (integer) > SADD web maiziedu.com (integer) > SADD web maiziedu.com (in ...

  5. js input复选框选中父级同时子级也选中

    js实现复选框选中父级元素子级元素也选中,没有子级元素选中父级也不选中的效果 HTML <tr> <td> <label> <input name=" ...

  6. 2 Sum

    Problem Given an array of integers, find two numbers such that they add up to aspecific target numbe ...

  7. ASC19超算概述

    初赛题目组成 设计超算集群(看参考文献做设计) 对超算集群进行性能测试(一般来讲的测试工具就是用HPL,找到最适合的参数,达到最优秀的计算能力) 数字图像处理(通常代码量较大,代码优化较为困难,优化偏 ...

  8. Codecraft-18 and Codeforces Round #458 (Div. 1 + Div. 2, combined) F. Substrings in a String

    http://codeforces.com/contest/914/problem/F 以前做过一个类似的,但是查询的子串长度最多是10,这个时候就是用bit + hash做了.这是因为改变一个字符, ...

  9. git使用笔记-提高篇-重置揭密

    https://git-scm.com/book/zh/v2/Git-%E5%B7%A5%E5%85%B7-%E9%87%8D%E7%BD%AE%E6%8F%AD%E5%AF%86 重置揭密 在继续了 ...

  10. 转:自定义控件三部曲之动画篇——alpha、scale、translate、rotate、set的xml属性及用法

    第一篇: 一.概述 Android的animation由四种类型组成:alpha.scale.translate.rotate,对应android官方文档地址:<Animation Resour ...