1,Valid Parentheses
1 bool isVaild1(string& s) { // 直接列举,不易扩展 2 stack<char> stk; 3 for (int i = 0; i < s.length(); ++i) { 4 if (stk.empty()) 5 stk.push(s[i]); 6 else { 7 char top = stk.top(); 8 if (top == '(' && s[i] == ')' || top == '{' && s[i] == '}' || top == '[' && s[i] == ']') 9 stk.pop(); 10 } 11 } 12 if (stk.empty()) 13 return true; 14 else 15 return false; 16 } 17 18 bool isValid2(string& s) { 19 string left = "([{"; 20 string right = ")]}"; 21 stack<char> stk; 22 23 for (auto c = s.begin(); c != s.end(); ++c) { 24 if (left.find(*c) != string::npos) 25 stk.push(*c); 26 else { 27 if (stk.empty() || stk.top() != left[right.find(*c)]) 28 return false; 29 else 30 stk.pop(); 31 } 32 } 33 return stk.empty(); 34 }