您的位置:首页 > 其它

Valid Parentheses

2015-09-08 08:44 204 查看
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.

题意:

有效括号:给定一个字符串仅包含字符’(’, ’)’, ’{’, ’}’, ’[’和 ’]’,判断输入的字符串是否有效。

必须以正确的符号结束。

分析:

基础知识:

string::npos

npos是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type

许多容器都提供这个东西。取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。

class Solution {
public:
bool isValid(string s) {
string left="([{";
string right=")]}";
stack<char> stk;
for(auto c:s)
{
if(left.find(c)!=string::npos)
{
stk.push(c);
}
else
{
if(stk.empty()||stk.top()!=left[right.find(c)])
return false;
else
stk.pop();
}
}
return stk.empty();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: