Valid Parentheses
2022-10-09T17:50:30 - Vicky Chhetri
Read Time:59 Second
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}"
Output: true
class Solution {
private:
int findLHS(char ch){
std::string s="([{";
return s.find(ch);
}
int findRHS(char ch){
std::string s=")]}";
return s.find(ch);
}
public:
bool isValid(string s) {
int len=s.length();
if(len==1 ||len%2!=0 ){
return false;
}
stack<char> stackI;
int i=0;
stackI.push(s[i++]);
while(i<len){
char ch1=s[i++];
size_t found=findLHS(ch1);
if(found !=string::npos){
stackI.push(ch1);
}else {
if(!stackI.empty()){
char ch2Prev= stackI.top();stackI.pop();
int i1=findLHS(ch2Prev);
int i2=findRHS(ch1);
if(i1!=i2){
return false;
}else {
continue;
}
}{
return false;
}
}
}
if(!stackI.empty()){
return false;
}
return true;
}
};