class Solution {
public:
const unordered_map<char, char> m = {
{')', '('},
{']', '['},
{'}', '{'}
};
bool isValid(string s) {
stack<char> st;
… // Your logic here
return s.empty();
}
};
You asked: "Why false?"
What's happening here?
At the end, your code returns:
return s.empty();
but you never modify s anywhere in the function (based on what you've shown).
If s is the input string, and you don't change it at all during the function, s.empty() will only be true if the input string was empty to begin with.
So for any non-empty string, s.empty() will be false, and the method will return false.
What usually needs to happen in a valid parentheses check?
Typically:
You iterate through each character of the input string s.
When you see an opening bracket '(', '[', or '{', push it onto the stack.
When you see a closing bracket ')', ']', or '}', check if the top of the stack matches its corresponding opening bracket.
If yes, pop from the stack.
If not, return false immediately.
At the end, return whether the stack is empty.
This way, the function returns true if all brackets matched correctly.
Correct minimal implementation example
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (m.count(c) == 0) {
// c is an opening bracket
st.push(c);
} else {
// c is a closing bracket
if (st.empty() || st.top() != m.at(c))
return false;
st.pop();
}
}
return st.empty();
}
Why your current function returns false for most inputs?
Because you don't modify s at all, so s.empty() remains false for non-empty input.
Also, you never examine st after building it, so stack content doesn't affect the return value.
Summary
You need to iterate through the string.
Use the stack to validate matching pairs.
Return whether the stack is empty at the end, not whether the input string s is empty.
If you want, I can help you write the entire function!