乘风破浪: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 ...
随机推荐
- C# 空合并运算符 ??
C#语言中,??运算符称为空合并运算符: a??b形式的空合并表达式要求a为可以为null的类型或引用类型.如果a为非null,则a??b的结果为a:否则,结果为b.仅当a为null时,该操作才计算b ...
- 【7】.net WebAPI Owin OAuth 2.0 密码模式验证实例
1.OAuth密码模式 2.在VS中创建WebAPI项目 在nuget中安装: Microsoft.AspNet.WebApi.Owin Microsoft.Owin.Host.SystemWeb 这 ...
- Vue2.0实现ie的兼容
转自:https://blog.csdn.net/landl_ww/article/details/79149461 1.解决方案:安装 "babel-polyfill" ,加配置 ...
- 一、cent OS安装配置JDK
到oracle官网下载JDKhttp://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html 在cent OS ...
- yum卸载
完全卸载依赖 -- 正常安装 yum install sl -- 列出操作 yum history list sl -- 根据显示install操作的id进行删除 yum history undo { ...
- zoj 1048
这道题提醒了我一个问题,怎么在while(cin>>a[i])下中断 #include<iostream> #include<cmath> #include< ...
- Java 集合:List(ArrayList,LinkedList)
- python学习之老男孩python全栈第九期_day025知识点总结——接口类、抽象类、多态、封装
一. 接口类 java:面向对象编程 设计模式 -- 接口类 接口类:python原生不支持 抽象类:python 原生支持的 from abc import abstractclassmethod, ...
- Mac(OS X)中Git安装与GitHub基本使用
GitHub是一个面向开源及私有软件项目的托管平台.开源代码库以及版本控制系统,因为只支持 Git 作为唯一的版本库格式进行托管,故名 GitHub.通常在Windows下使用GitHub的教程是非常 ...
- 从JSON中读取数据追加到HTML中
本文来自https://www.jianshu.com/p/04127d74d88c,并非本人原创,只是作为自己学习使用的资料,如有浏览者请点击地址自行到原作者页面浏览 有时候我们需要将json数据直 ...