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

【Leetcode】Valid Parentheses

时间:2016-06-06 01:10:09      阅读:142      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!