您的位置:首页 > 编程语言 > C语言/C++

LeetCode 之 Valid Parentheses — C++ 实现

2015-06-11 10:44 786 查看


Valid Parentheses

 

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.
给定一个只包含
'('
')'
'{'
'}'
'['
 和']' 的字符串,验证字符串是否有效。
括号必须以正确的顺序关闭,如
"()" 和
"()[]{}" 合法,"(]" 和"([)]" 不合法。

分析:

使用堆栈,遇到左括号入栈,遇到右括号出栈,若和右括号匹配则继续比较,否则不合法;如果比较完后堆栈中还剩下未匹配的括号,说明存在左括号没有闭合,也不合法。

class Solution {
public:
bool isValid(string s) {
stack<char> hasNotMatch;
int index = 0;
int strLen = s.length();

if(s.empty()) //空字符串,匹配
return true;

for(; index < strLen; ++index)
{
switch(s[index])
{
//左括号直接压栈,不用比较
case '(':
case '[':
case '{':
{
hasNotMatch.push(s[index]);
}
break;
//每出现一个右括号,匹配一次
case ')':
{
if(hasNotMatch.empty()) //栈空,没有待匹配德左括号
return false;
if(hasNotMatch.top() == '(')//匹配,出栈
{
hasNotMatch.pop();
}
else
return false;
}
break;
case ']':
{
if(hasNotMatch.empty())
return false;
if(hasNotMatch.top() == '[')//匹配,出栈
{
hasNotMatch.pop();
}
else
return false;
}
break;
case '}':
{
if(hasNotMatch.empty())
return false;
if(hasNotMatch.top() == '{')//匹配,出栈
{
hasNotMatch.pop();
}
else
return false;
}
break;
default:
break;
}
}
if(!hasNotMatch.empty())//栈中剩有不匹配的左括号
{
return false;
}

return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息