《leetcode》valid-parentheses
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》valid-parentheses
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
Given a string containing just the characters’(‘,’)’,’{‘,’}’,’[‘and’]’, determine if the input string is valid.
The brackets must close in the correct order,”()”and”()[]{}”are all valid but”(]”and”([)]”are not.
解析:利用棧進行匹配,詳情見代碼注解
public static boolean isValid(String s) {Stack<Character> stack = new Stack<>();Character temp;for(int i=0;i<s.length();i++){temp=s.charAt(i);if(temp=='('||temp=='['||temp=='{'){//當前字符是左括號,入棧stack.push(temp);}else {if(stack.isEmpty()){//當前括號是右括號,棧空說明沒有左括號return false;}Character top=stack.peek();//取棧頂元素if(temp==')'){//需要判斷當前元素與棧頂元素的匹配情況,例如:"([)]" 返回:falseif(top=='('){stack.pop();}}else if(temp==']'){if(top=='['){stack.pop();}}else {stack.pop();}}}return stack.isEmpty();//棧空則說明全部匹配了}總結
以上是生活随笔為你收集整理的《leetcode》valid-parentheses的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《leetcode》pascals-tr
- 下一篇: 《leetcode》remove-dup