【Leetcode】Valid Parentheses

题目链接: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)