Skip to content

Emmanuel Brun d'Aubignosc's site about software engineering

This is my personal blog about software and algorithms

Menu
  • About
Menu

Leecode Valid Parentheses C++

Posted on September 7, 2023 by Emmanuel Brun d'Aubignosc

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.

class Solution {
public:
    bool isValid(string s) {
        char tmpchar;
        std::stack<char> st;
        int counter = 0;
        
        for (int i = 0; i < s.length(); i ++) {
            
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                
                st.push(s[i]);
                counter ++;
            }
            
            if (s[i] == ')' || s[i] == ']' || s[i] == '}') {

                if (counter < 1) {                    
                    return false;
                }

                tmpchar = st.top();
                st.pop();
                
                if ((s[i] == ')' && tmpchar != '(')
                        || (s[i] == ']' && tmpchar != '[')
                        || (s[i] == '}' && tmpchar != '{'))
                {
                    return false;
                }
                
                counter --;
            }        
        }
        
        return counter == 0;
    }
};

Related

Recent Posts

  • Leecode Valid Parentheses C++
  • Leetcode Two Sums Java
  • Leetcode Two Sums C++
  • Quick sort using modern C++

Recent Comments

No comments to show.

Archives

  • September 2023
  • August 2023

Categories

  • Leetcode
  • Uncategorized
© 2025 Emmanuel Brun d'Aubignosc's site about software engineering | Powered by Minimalist Blog WordPress Theme