【Leetcode】【Easy】Valid Parentheses

Given a string containing just the characters '('')''{', '}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解题思路:

栈使用的典型题目;

解题步骤:

1、新建一个栈;

2、遍历字符串:

  (1)符号的左半边,则入栈;

  (2)符号的右半边,则pop出栈顶元素,如果栈为空,则返回false;

     判断此右半边和栈顶元素是否匹配;匹配继续;不匹配则返回false;

 3、循环结束后栈为空,则true,不为空则false;

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> st;
 5         int len = s.length(); 
 6         
 7         for(int i = 0; i < len; ++i) {
 8             if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
 9                 if (st.empty()) 
10                     return false;
11                 char c = st.top();
12                 if ((c == '(' && s[i] != ')') || 
13                     (c == '[' && s[i] != ']') || 
14                     (c == '{' && s[i] != '}'))
15                     return false;
16                 st.pop();
17                 
18             } else {
19                 st.push(s[i]);
20             }
21         }
22         
23         return st.empty();
24     }
25 };

附录:

常见符号ASCII码

C++常见容器使用及公式

原文地址:https://www.cnblogs.com/huxiao-tee/p/4225167.html