乘风破浪:LeetCode真题_020_Valid Parentheses

一、前言

下面开始堆栈方面的问题了,堆栈的操作基本上有压栈,出栈,判断栈空等等,虽然很简单,但是非常有意义。

二、Valid Parentheses

2.1 问题

2.2 分析与解决

    我们可以看到通过堆栈,先压进符号的左半部分,然后如果下次直接是该符号的右半部分,那就弹出左半部分,否则继续压入符号的左半部分,如果此时是其他符号的右半部分,那就是错误了。每一次当形成一个整体的时候都会被弹出去,这样就能直接判断了。

class Solution {

  // Hash table that takes care of the mappings.
private HashMap<Character, Character> mappings; // Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
} public boolean isValid(String s) { // Initialize a stack to be used in the algorithm.
Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); // If the current character is a closing bracket.
if (this.mappings.containsKey(c)) { // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop(); // If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}
} // If the stack still contains elements, then it is an invalid expression.
return stack.isEmpty();
}
}

     上面的代码已经很清晰了,当然我们也可以这样表述:

import java.util.Deque;
import java.util.LinkedList; public class Solution {
/**
*
* 题目大意
* 给定一个只包含(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和‘]’的字符串,验证它是否是有效的。
* 括号必须配对,并且要以正确的顺序。
*
* 解题思路
* 用一个栈来对输入的括号串进行处理,如果是左括号就入栈,如果是右括号就与栈顶元素看是否组成一对括号,
* 组成就弹出,并且处理下一个输入的括号,如果不匹配就直接返回结果。
*/
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
int index = 0;
Character top;
while (index < s.length()) {
Character c = s.charAt(index);
switch (c) {
case '(':
case '[':
case '{':
stack.addFirst(c);
break;
case ')': if (stack.isEmpty()) {
return false;
} top = stack.getFirst();
if (top == '(') {
stack.removeFirst();
} else if (top == '[' || top == '{') {
return false;
} else {
stack.addFirst(c);
}
break;
case ']': if (stack.isEmpty()) {
return false;
} top = stack.getFirst();
if (top == '[') {
stack.removeFirst();
} else if (top == '(' || top == '{') {
return false;
} else {
stack.addFirst(c);
}
break;
case '}': if (stack.isEmpty()) {
return false;
} top = stack.getFirst();
if (top == '{') {
stack.removeFirst();
} else if (top == '[' || top == '(') {
return false;
} else {
stack.addFirst(c);
}
break;
default:
return false;
} index++;
} return stack.isEmpty();
}
}

三、总结

通过对堆栈的练习,我们复习了一些基础知识,同时对于这些涉及表达式的运算,类似于树的遍历,我们都要想到堆栈来解决。

乘风破浪:LeetCode真题_020_Valid Parentheses的更多相关文章

  1. 乘风破浪:LeetCode真题_022_Generate Parentheses

    乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...

  2. 乘风破浪:LeetCode真题_032_Longest Valid Parentheses

    乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...

  3. 乘风破浪:LeetCode真题_041_First Missing Positive

    乘风破浪:LeetCode真题_041_First Missing Positive 一.前言 这次的题目之所以说是难,其实还是在于对于某些空间和时间的限制. 二.First Missing Posi ...

  4. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  5. 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum 一.前言     这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...

  6. 乘风破浪:LeetCode真题_038_Count and Say

    乘风破浪:LeetCode真题_038_Count and Say 一.前言     这一道题目,很类似于小学的问题,但是如果硬是要将输入和结果产生数值上的联系就会产生混乱了,因此我们要打破思维定势. ...

  7. 乘风破浪:LeetCode真题_037_Sudoku Solver

    乘风破浪:LeetCode真题_037_Sudoku Solver 一.前言 这次我们对于上次的模型做一个扩展并求解. 二.Sudoku Solver 2.1 问题 2.2 分析与解决     这道题 ...

  8. 乘风破浪:LeetCode真题_036_Valid Sudoku

    乘风破浪:LeetCode真题_036_Valid Sudoku 一.前言 有的时候对于一些基础知识的掌握,对我们是至关重要的,比如ASCII重要字符的表示,比如一些基本类型的长度. 二.Valid ...

  9. 乘风破浪:LeetCode真题_035_Search Insert Position

    乘风破浪:LeetCode真题_035_Search Insert Position 一.前言 这次的问题比较简单,也没有限制时间复杂度,但是要注意一些细节上的问题. 二.Search Insert ...

随机推荐

  1. np.random.random()函数 参数用法以及numpy.random系列函数大全

    原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9751471.html 1.np.random.random()函数参数 np.random.r ...

  2. RabbitMQ的安装和配置化可视界面

    RabbitMQ在windows下的安装 RabbitMQ 它依赖于Erlang,在window上安装时,需要先安装Erlang. 首先确定你的window电脑是32位还是64位,然后下载对应版本的E ...

  3. 64位使用windbg获取Shadow SSDT

    首先选择一个带界面的程序explorer.exe进行附加 kd> !process explorer.exe PROCESS ffff86893dd075c0 SessionId: Cid: 0 ...

  4. jquery里判断数组内是否包含了指定的值或元素的方法

    本文讲的是在jquery里,如何判断一个数组里是否包含了指定的值,变量,或其它对象元素的方法. 在jquery里,我们可以用$.inArray来判断一个数组里是否包含了指定的值或其它对象元素,来看一个 ...

  5. table 中的tr 行点击 变换颜色背景

    <style> table{border-collapse: collapse;border-spacing: 0; width: 100%;} table tr th,td{border ...

  6. 三、hbase JavaAPI

    hbase是Java编写的,当然也提供了Java的API来操作hbase. 如果你是使用虚拟机来安装配置hbase那么你需要配置一下hostname,不然JavaAPI访问虚拟机的时候会无法连接,请参 ...

  7. groovy函数、字符串、循环

    三重单引号字符串 '''a triple single quoted string''' 三重单引号字符串是普通的java.lang.String 三重单引号字符串是多行的.您可以跨越行边界跨越字符串 ...

  8. Mac(OS X)中Git安装与GitHub基本使用

    GitHub是一个面向开源及私有软件项目的托管平台.开源代码库以及版本控制系统,因为只支持 Git 作为唯一的版本库格式进行托管,故名 GitHub.通常在Windows下使用GitHub的教程是非常 ...

  9. sql:PostgreSQL

    PostgreSQL sql script: -- Database: geovindu -- DROP DATABASE geovindu; CREATE DATABASE geovindu WIT ...

  10. UOJ#172. 【WC2016】论战捆竹竿

    传送门 首先这个题目显然就是先求出所有的 \(border\),问题转化成一个可行性背包的问题 一个方法就是同余类最短路,裸跑 \(30\) 分,加优化 \(50\) 分 首先有个性质 \(borde ...