乘风破浪: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. python-wsgi测试服务器

    #!/usr/bin/python from wsgiref.simple_server import make_server def application(environ,start_respon ...

  2. Python36和Python27共存的方法

    Python26和Python37环境的配置 设置环境变量 我的电脑右键属性-高级系统属性-环境变量 选择系统变量中的Path,双击打开 加入你的Python安装路径 C:\Python27;C:\P ...

  3. The servlets named [create_subscription] and [servlet.create] are both mapped to the url-pattern [/create] which is not permitted [duplicate]

    原因,代码中在public前已经有了默认的配置路径: 如: @WebServlet("/ShowUser")public class ShowUser extends HttpSe ...

  4. MVC缓存(一)

    //OutputCache是设置缓存,参数Duration设置缓存的过期时间,OutputCache可以加到Controller上,也可以加到Action上,但是当Controller与Action都 ...

  5. vs2015编译时CS1056 C# Unexpected character解决办法

    https://stackoverflow.com/questions/42932577/error-cs1056-unexpected-character-running-the-msbuild-o ...

  6. 让图片在div中居中

    详情看:https://www.cnblogs.com/yyh1/p/5999152.html

  7. Cheatsheet: 2018 08.01 ~ 2018 10.31

    Other Building the Ultimate Developer PC 3.0 - The Parts List for my new computer, IronHeart Face re ...

  8. 六、阻塞队列LinkedBlockQueue

    一.简介 Java提供了FIFO先进先出的阻塞队列实现,这其实是一种生产者消费者理念,可以通过阻塞队列将生产者和消费者进行解耦合. LinkedBlockQueue是一种无界队列,但事实上它只是队列可 ...

  9. 解决-word里无论怎么改变字体颜色,字体总是红色的

    1.你遇到的问题是Word当前处于审阅状态,修改的内容显示为红色字体.2.解决办法是退出Word审阅状态,或者接受全部修订.3.不同Word版本的审阅模式不同,可在菜单栏里退出审阅,或者按鼠标右键弹出 ...

  10. springboot在阿里CentOS 7后台永久运行

    查看Java进程可以使用 ps -ef|grep java 首次后台永久启动,会把日志输出到新建的log.file文件 nohup java -jar demo-0.0.1-SNAPSHOT.jar ...