《leetcode》valid-parentheses
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》valid-parentheses
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
Given a string containing just the characters’(‘,’)’,’{‘,’}’,’[‘a(chǎn)nd’]’, determine if the input string is valid.
The brackets must close in the correct order,”()”and”()[]{}”are all valid but”(]”and”([)]”are not.
解析:利用棧進(jìn)行匹配,詳情見(jiàn)代碼注解
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=='{'){//當(dāng)前字符是左括號(hào),入棧stack.push(temp);}else {if(stack.isEmpty()){//當(dāng)前括號(hào)是右括號(hào),棧空說(shuō)明沒(méi)有左括號(hào)return false;}Character top=stack.peek();//取棧頂元素if(temp==')'){//需要判斷當(dāng)前元素與棧頂元素的匹配情況,例如:"([)]" 返回:falseif(top=='('){stack.pop();}}else if(temp==']'){if(top=='['){stack.pop();}}else {stack.pop();}}}return stack.isEmpty();//棧空則說(shuō)明全部匹配了}總結(jié)
以上是生活随笔為你收集整理的《leetcode》valid-parentheses的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 《leetcode》pascals-tr
- 下一篇: 《leetcode》remove-dup