1. Valid parentheses (Easy)🔗
Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective. A valid string must meet the following requirements:
- An open parenthesis must be closed with a close parenthesis of the same type.
- The left parentheses must be closed in the correct order.
Example 1:
Input: s = "([)]" Output: falseCopy the code
Example 2:
Input: s = "{[]}" Output: trueCopy the code
😁 analysis
Take advantage of the properties of the stack.
😋 code
class Solution {
private:
stack<char> stk;
public:
bool isValid(string s) {
int len = s.length(a);for (int i = 0; i < len; i++) {
char t = s[i];
if (t == '(' || t == '[' || t == '{') {
stk.push(t);
} else {
if (stk.empty()) return false;
else {
int pop_s = stk.top(a);if ( (t == ') ' && pop_s == '(') || (t == '] ' && pop_s == '[') ||
(t == '} ' && pop_s == '{') ) {
stk.pop(a); }else {
return false; }}}}return stk.empty();
}
};
Copy the code