您的位置:首页 > 其它

leetcode:Valid Parentheses(有效括号匹配)

2013-10-24 16:57 387 查看
Question:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: