leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
2017-05-22 17:44
405 查看
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
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.
思路:题目整体上比較明白,是对括号是否有效做推断,算法上是用栈来实现,单边入栈。配对之后出栈,最后推断栈是否为空。不为空说明最后没有配对完毕。返回false.
详细代码例如以下:
public class Solution { public boolean isValid(String s) { Stack<Character> st = new Stack<Character>(); char[] ch = s.toCharArray(); int len = ch.length; //假设长度为奇数,肯定无效 if((len & 1) != 0){ return false; } for(int i = 0; i < len; i++){ if(st.isEmpty()){//栈为空,直接入栈 st.push(ch[i]); }else{//不为空则讨论栈顶元素是否与ch[i]配对。配对也出栈 if(isMatch(st.peek(),ch[i])){//是否配对 st.pop();//栈顶元素出栈 }else{ st.push(ch[i]);//不配对入栈 } } } return st.isEmpty(); } //a为栈顶元素,b为字符串最前元素 public static boolean isMatch(char a, char b){ switch(a){ case '(': if(b == ')') return true; else return false; case '{': if(b == '}') return true; else return false; case '[': if(b == ']') return true; else return false; default : return false; } } }
相关文章推荐
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- leetCode 32.Longest Valid Parentheses (有效的最大括号) 解题思路和方法
- LeetCode 20. Valid Parentheses--验证括号是否有效
- leetcode20 Valid Parentheses 有效的括号
- LeetCode 20 Valid Parentheses(有效的括号)
- LeetCode-20-Valid Parentheses(有效的括号)
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- 【LeetCode-面试算法经典-Java实现】【032-Longest Valid Parentheses(最长有效括号)】
- [LeetCode]35. Valid Parentheses有效括号
- 最长连续有效括号 Longest Valid Parentheses @LeetCode
- Leetcode刷题记——32. Longest Valid Parentheses(最长有效括号)
- leetcode 20 Valid Parentheses 括号匹配
- Leet Code 20 Valid Parentheses - 有效括号 - Java
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- 【LeetCode】- Valid Parentheses(有效的括号)
- [LeetCode] Longest Valid Parentheses 解题思路
- LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)
- [LeetCode]39. Longest Valid Parentheses最长有效括号对
- [Leetcode] 20. Valid Parentheses 解题报告
- LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)