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. A. The number of positions

    A. The number of positions time limit per test 0.5 second memory limit per test 256 megabytes input ...

  2. Python读写操作Excel模块_xlrd_xlwt_xlutils

    Python 读写操作Excel -- 安装第三方库(xlrd.xlwt.xlutils.openpyxl) 如果仅仅是要以表单形式保存数据,可以借助 CSV 格式(一种以逗号分隔的表格数据格式)进行 ...

  3. Problem01 不死神兔

    题目:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少? 程序分析:兔子的规律为数列1,1,2,3,5,8,13,21 ...

  4. vue入门----------路由配置

    在使用脚手架搭建好项目后要配置路由 1.首先要安装vue-router,你可以在项目的package.json文件中的dependencies项目中添加"vue-route": & ...

  5. Mybatis学习笔记12 - 动态sql之choose(when otherwise)标签

    choose (when, otherwise):分支选择:带了break的swtich-case 示例代码: 接口定义: package com.mybatis.dao; import com.my ...

  6. android Firebase中配置 Crashlytics

    首先登陆Google账号 https://firebase.google.com/ 创建项目 配置Android 1.注册应用 2.下载配置文件 3.添加firebaseSDk 配置后台分析的Cras ...

  7. Python字符和编码

    1. 字符和编码 背景 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节(byte). 由于计算机是美国人发明的,因此, ...

  8. 2019.03.21 读书笔记 readonly与const

    区别: const是编译时常量(指反编译时看到的源码是常量本身,而不是变量),自带static,只能修饰基元类型.枚举.字符串,readonly是运行时常量(全局变量或者构造赋值),不受类型限制,但在 ...

  9. 3d Max 2014安装失败怎样卸载3dsmax?错误提示某些产品无法安装

    AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...

  10. caffe学习资料

    1.利用Caffe做回归(regression) http://www.cnblogs.com/frombeijingwithlove/p/5314042.html