leetcode:Valid Parentheses(有效括号匹配)
2013-10-24 16:57
387 查看
Question:
Given a string containing just the characters
The brackets must close in the correct order,
给定一个字符串仅仅包含这些字符
算法思想:① 这个题首先会想到用栈进行存储操作,遇到左边的字符‘[’,'{',‘(’则进栈,如果遇到相反字符在栈不为空的前提下出栈,并且判断读到的字符是否和出栈的字符匹配,匹配的话继续,否则直接结束。
② 有一点儿在遍历输入字符时,如果栈为空了,表明肯定不能匹配。
③ 如果输入的字符遍历完毕,但是栈不为空,表明‘[’,'{',‘(这些字符多,也肯定不匹配。
代码设计:
2013-10-2402:16:14
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.
给定一个字符串仅仅包含这些字符
'(',
')',
'{',
'}',
'['and
']', 判定输入的字符串是否是可匹配的,括号必须以正确的顺序打开关闭,比如"()"and
"()[]{}"。
算法思想:① 这个题首先会想到用栈进行存储操作,遇到左边的字符‘[’,'{',‘(’则进栈,如果遇到相反字符在栈不为空的前提下出栈,并且判断读到的字符是否和出栈的字符匹配,匹配的话继续,否则直接结束。
② 有一点儿在遍历输入字符时,如果栈为空了,表明肯定不能匹配。
③ 如果输入的字符遍历完毕,但是栈不为空,表明‘[’,'{',‘(这些字符多,也肯定不匹配。
代码设计:
class Solution { public boolean isValid(String s) { // Note: The Solution object is instantiated only once and is reused by each test case. if(s.length()%2==1) return false;//如果是奇数,一定不匹配 Stack<Character> stack=new Stack<Character>(); Character temp=null; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='{'||s.charAt(i)=='['||s.charAt(i)=='('){ stack.push(s.charAt(i));//满足条件进栈 } if(s.charAt(i)=='}'||s.charAt(i)==']'||s.charAt(i)==')'){ if(!stack.isEmpty()) temp=stack.pop(); //满足上述条件,出栈 else return false;//循环还没结束 栈空了 一定不匹配 if((temp=='{'&&s.charAt(i)=='}')||(temp=='('&&s.charAt(i)==')')||(temp=='['&&s.charAt(i)==']')){ continue; //表示匹配,可以继续往下进行 } else{ return false; //不匹配。直接结束 } } } if(stack.isEmpty()) //有可能字符串已经遍历结束,但是栈并不为空,这表示不匹配,如果匹配的话肯定是栈为空并且字符串遍历完毕 return true; else return false; } }
2013-10-2402:16:14
相关文章推荐
- LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度
- [LeetCode]39. Longest Valid Parentheses最长有效括号对
- LeetCode 32 Longest Valid Parentheses (栈,括号匹配)
- Longest Valid Parentheses (求最长有效匹配括号子串的长度)
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- Leetcode刷题记——32. Longest Valid Parentheses(最长有效括号)
- LeetCode-32.Longest Valid Parentheses最长有效括号子串
- [LeetCode]35. Valid Parentheses有效括号
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- [Leetcode] longest valid parentheses 最长的有效括号
- leetcode 20 Valid Parentheses 括号匹配
- Longest Valid Parentheses(最长的括号匹配)【面试算法leetcode】
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- 【LeetCode】- Valid Parentheses(有效的括号)
- [Leetcode] valid parentheses 有效括号对
- LeetCode-20-Valid Parentheses(有效的括号)
- LeetCode-Longest Valid Parentheses-最长匹配括号-栈的应用