20 Valid Parentheses
生活随笔
收集整理的這篇文章主要介紹了
20 Valid Parentheses
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 題目理解
輸入:一個(gè)字符串s,只包含( ) { } [ ]這六種字符。
輸出:字符串是否有效
規(guī)則:一個(gè)有效的字符串需要括號(hào)對(duì)應(yīng)匹配,并且要左括號(hào)在前。
舉例:
1 輸入s="()",輸出true
2 Input: s = “()[]{}”
Output: true
3 Input: s = “(]”
Output: false
2思路
這道題目比較簡(jiǎn)單。用棧記錄出現(xiàn)過的左括號(hào),遇到右括號(hào)的時(shí)候去匹配。不能匹配上就是無效的。
class Solution {public boolean isValid(String s) {Map<Character,Character> map = new HashMap<Character,Character>();map.put(')','(');map.put(']','[');map.put('}','{');Stack<Character> stack = new Stack<Character>();for(int i=0;i<s.length();i++){char ch = s.charAt(i);if(map.get(ch)!=null){if(stack.isEmpty() || stack.peek()!=map.get(ch)){return false;}stack.pop();}else{stack.push(ch);}}return stack.isEmpty();} }總結(jié)
以上是生活随笔為你收集整理的20 Valid Parentheses的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hash(LCP) || 后缀数组 LA
- 下一篇: 机器学习与人类比较