LeetCode算法入门- Valid Parentheses -day11
题目描述:
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
思路分析:
题目的意思是给定一个包含一系列括号的字符串,判断其中的括号是否两两匹配。
可以相等用堆这个结构来实现,遇到左方向括号就入栈,有方向就判断栈顶是否为对应的左方向括号,并且出栈,如果不是就直接返回false
Java代码如下:
class Solution {public boolean isValid(String s) {Stack<Character> stack = new Stack<>();for(int i = 0; i < s.length(); i++){if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){stack.push(s.charAt(i));}//记得判断堆栈是否为空,为空的话也要返回falseelse if(stack.isEmpty()){return false;}else if(s.charAt(i) == ')' && stack.peek() != '('){return false;}else if(s.charAt(i) == ']' && stack.peek() != '['){return false;}else if(s.charAt(i) == '}' && stack.peek() != '{'){return false;}else{//同时这里也要记得将其弹出来stack.pop();}}//最后通过判断堆是否为空来确实是否符合条件return stack.isEmpty();}
}