首页 > 其他 > 详细

【Leetcode】Valid Parentheses

时间:2016-06-06 01:08:02      阅读:136      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/problems/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.

思路:

用栈,easy。。

算法

[java] view plain copy
 技术分享技术分享
  1. public boolean isMatch(char c1, char c2) {  
  2.     if (c1 == ‘(‘ && c2 == ‘)‘)  
  3.         return true;  
  4.     if (c1 == ‘[‘ && c2 == ‘]‘)  
  5.         return true;  
  6.     if (c1 == ‘{‘ && c2 == ‘}‘)  
  7.         return true;  
  8.     return false;  
  9. }  
  10.   
  11. public boolean isValid(String s) {  
  12.     Stack<Character> stk = new Stack<Character>();  
  13.     char c[] = s.toCharArray();  
  14.     for (char i : c) {  
  15.         if (!stk.isEmpty()) {  
  16.             char t = (char) stk.pop();  
  17.             if (!isMatch(t, i)) {// 如果可以抵消  
  18.                 stk.push(t);  
  19.                 stk.push(i);  
  20.             }  
  21.         } else {  
  22.             stk.push(i);  
  23.         }  
  24.     }  
  25.     if (!stk.isEmpty())  
  26.         return false;  
  27.     else  
  28.         return true;  
  29. }  

【Leetcode】Valid Parentheses

原文:http://blog.csdn.net/yeqiuzs/article/details/51590938

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!