0 0
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:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. 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;
    }
};
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *