LeetCode [20. Valid Parentheses]
I tried to solve 20. ‘Valid Parentheses’.
Problem
20. Valid Parentheses
My idea
I use stack
. next char should correspond last char.
Correct Solution
class Solution {
public:
bool isValid(string ss) {
map<char,char> cor{
{'(',')'},
{'{','}'},
{'[',']'}
};
vector<char> stack;
for(const auto& s : ss){
if(s == '(' || s == '[' || s == '{'){
stack.push_back(s);
}else if(s == ')' || s == ']' || s == '}'){
if(stack.empty()){ return false; }
if(cor[stack.back()] != s){
return false;
}
stack.pop_back();
}
}
return stack.empty();
}
};
My wrong idea
In first, I think sum of ‘(’,’[‘,’{’ equals sum of ‘)’,‘]’,‘}’.
but this test case is failed.
Input: "([)]"
Output: true
Expected: false
bool isValid(string ss) {
auto mn = 0;
auto sn = 0;
auto nn = 0;
for(const auto& s : ss){
if(s == '('){
mn++;
}else if(s == '['){
sn++;
}else if(s == '{'){
nn++;
}else if(s == ')'){
if(mn == 0){ return false; }
mn--;
}else if(s == ']'){
if(sn == 0){ return false; }
sn--;
}else if(s == '}'){
if(nn == 0){ return false; }
nn--;
}
}
return (mn == 0 && sn == 0 && nn == 0);
}
Read other posts