码迷,mamicode.com
首页 > 其他好文 > 详细

20. Valid Parentheses

时间:2017-02-03 10:46:15      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:info   ota   racket   bool   res   als   ret   when   span   

20. Valid Parentheses

  • Total Accepted: 167254
  • Total Submissions: 517330
  • Difficulty: Easy
  • Contributors: Admin

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.

Solution:

Use stack. When we meet a left parentheses, we push it into the stack. When we meet a right parentheses, we will return false if the stack is empty, otherwise, we will pop the top of the stack to find if it is the corresponding left parentheses.

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> st;
 5         for(int i = 0; i < s.size(); i++){
 6             if(s[i] == ( || s[i] == { || s[i] == [){
 7                 st.push(s[i]);
 8             }else if(s[i] == ) || s[i] == } || s[i] == ]){
 9                 if(st.empty()){
10                     return false;
11                 }else{//只需判断false的情况,最后再pop就可以了
12                     if(s[i] == ) && st.top() != () return false;
13                     if(s[i] == ] && st.top() != [) return false;
14                     if(s[i] == } && st.top() != {) return false;
15                     st.pop();
16                 }
17             }
18         }
19         //return true;此时不能直接return true,因为stack里可能会有剩余的左括号
20         return st.empty();
21     }
22 };

 

 

 

 

 

 

20. Valid Parentheses

标签:info   ota   racket   bool   res   als   ret   when   span   

原文地址:http://www.cnblogs.com/93scarlett/p/6362009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!