class Solution {
public:
bool isValid(string s) {
map<char, char> m = {{'}', '{'}, {')', '('}, {']', '['}};
stack<char> t;
if(s.size() == 0)
return false;
for(int i = 0; i < s.size(); ++i)
{
if(m.find(s[i]) != m.end())
{
if(t.empty())
{
return false;
}
if(m[s[i]] != t.top())
{
return false;
}
else
{
t.pop();
}
}
else
{
t.push(s[i]);
}
}
if(t.empty())
return true;
else
return false;
}
};
为什么我总是写这么长……而且总是有很多if语句…………看到别人写了一个看起来简单的java版本,改成C++:
class Solution {
public:
bool isValid(string s) {
stack<char> charstack;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] == '(')
charstack.push(')');
else if(s[i] == '{')
charstack.push('}');
else if(s[i] == '[')
charstack.push(']');
else if(charstack.empty() || charstack.top() != s[i])
return false;
else
charstack.pop();
}
return charstack.empty();
}
};
这个看起来就逻辑清晰,我写的逻辑很乱。