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();
}
};