乘风破浪:LeetCode真题_020_Valid Parentheses
乘风破浪: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的更多相关文章
- 乘风破浪:LeetCode真题_022_Generate Parentheses
乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...
- 乘风破浪:LeetCode真题_032_Longest Valid Parentheses
乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...
- 乘风破浪:LeetCode真题_041_First Missing Positive
乘风破浪:LeetCode真题_041_First Missing Positive 一.前言 这次的题目之所以说是难,其实还是在于对于某些空间和时间的限制. 二.First Missing Posi ...
- 乘风破浪:LeetCode真题_040_Combination Sum II
乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...
- 乘风破浪:LeetCode真题_039_Combination Sum
乘风破浪:LeetCode真题_039_Combination Sum 一.前言 这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...
- 乘风破浪:LeetCode真题_038_Count and Say
乘风破浪:LeetCode真题_038_Count and Say 一.前言 这一道题目,很类似于小学的问题,但是如果硬是要将输入和结果产生数值上的联系就会产生混乱了,因此我们要打破思维定势. ...
- 乘风破浪:LeetCode真题_037_Sudoku Solver
乘风破浪:LeetCode真题_037_Sudoku Solver 一.前言 这次我们对于上次的模型做一个扩展并求解. 二.Sudoku Solver 2.1 问题 2.2 分析与解决 这道题 ...
- 乘风破浪:LeetCode真题_036_Valid Sudoku
乘风破浪:LeetCode真题_036_Valid Sudoku 一.前言 有的时候对于一些基础知识的掌握,对我们是至关重要的,比如ASCII重要字符的表示,比如一些基本类型的长度. 二.Valid ...
- 乘风破浪:LeetCode真题_035_Search Insert Position
乘风破浪:LeetCode真题_035_Search Insert Position 一.前言 这次的问题比较简单,也没有限制时间复杂度,但是要注意一些细节上的问题. 二.Search Insert ...
随机推荐
- python-TCP模拟ftp文件传输
#!/usr/bin/python #coding=utf-8 #server from socket import* import sys,os def command(): l=[ "W ...
- 使用C++11 开发一个半同步半异步线程池
摘自:<深入应用C++11>第九章 实际中,主要有两种方法处理大量的并发任务,一种是一个请求由系统产生一个相应的处理请求的线程(一对一) 另外一种是系统预先生成一些用于处理请求的进程,当请 ...
- 在spring中常被忽视的注解 @Primary
在spring 中使用注解,常使用@Autowired, 默认是根据类型Type来自动注入的. 但有些特殊情况,对同一个接口,可能会有几种不同的实现类,而默认只会采取其中一种的情况下 @Primary ...
- Perl入门
Perl 是一门开源的脚本语言,由 Larry Wall 所创造,该语言以实用,快速开发为主要目标,与当前流行的面向对象结构化编程有些格格不入,但这并不妨碍 Perl 被广泛流传和使用,世界范围内围绕 ...
- 八段代码彻底掌握 Promise
1.Promise的立即执行性 var p = new Promise(function(resolve, reject){ console.log("create a promise&qu ...
- MFC—— AfxMessageBox
AfxMessageBox 错误C2665: “AfxMessageBox”: 2 个重载中没有一个可以转换所有参数类型 1,楼主发表于:2007-01-01 03:56:34同样的语句, ...
- 引入第三方js文件,报错
错误:Mixed Content: The page at 'https://localhost:44336/MENU' was loaded over HTTPS, but requested an ...
- Cause: com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型。
mybatis执行sqlserver的sql报错 com.microsoft.sqlserver.jdbc.SQLServerException: 不支持“variant”数据类型. at com.m ...
- js事件队列
前面跟网友讨论到了JS的事件队列 ,对这个有了一些理解,事件队列我认为就是把一些不按顺序执行的事件放到队列里面,然后按照自己制定的顺序去执行,那么什么情况下会用到这个呢?我首先想到的是动画,动画是会执 ...
- [POI2005]AUT-The Bus
树状数组维护前缀最大值+扫描线DP #include"cstdio" #include"cstring" #include"iostream" ...