LeetCode算法入门- Valid Parentheses -day11
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();} }總結
以上是生活随笔為你收集整理的LeetCode算法入门- Valid Parentheses -day11的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode(#1)————Two
- 下一篇: 两个摄像头合成一路_教你把一个摄像机添加