首页 > 代码库 > Leetcode 20. Valid Parentheses

Leetcode 20. Valid Parentheses

20. Valid Parentheses

  • Total Accepted: 128586
  • Total Submissions: 418560
  • Difficulty: Easy

 

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.

 

思路:利用栈来判断配对的括号,如果都可以配对成功,最后栈的元素数量应该为0。题目给定的字符串只包含括号,所以每次遇到是(‘, ‘{‘或者‘[‘,直接入栈;遇到‘]‘,‘)‘或者‘]‘,只有当栈不为空&&栈顶元素与之配对时,才弹出栈,否则直接返回false。

 

代码:

 1 class Solution { 2 public: 3     bool isValid(string s) { 4         stack<char> cs; 5         unordered_map<char, char> um; 6         um[(] = ); 7         um[{] = }; 8         um[[] = ]; 9         for (int i = 0; i < s.size(); i++) {10             if (s[i] == ( || s[i] == { || s[i] == [) {11                 cs.push(s[i]);12                 continue;13             }14             if (!cs.empty() && um[cs.top()] == s[i]){15                 cs.pop();16                 continue;17             } 18             return false;19         }20         return cs.empty();21     }22 };

 

Leetcode 20. Valid Parentheses