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

Valid Parentheses

时间:2015-10-08 22:54:33      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:

判断括号是否符合标准

这个问题思路很简单,判断右括号能不能对的上最括号就行

堆栈是个好东西

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.

 

 1 package com.rust.TestString;
 2 
 3 import java.util.Stack;
 4 
 5 public class ValidParentheses {
 6 
 7     public static boolean isValid(String s) {
 8         if(s.length() == 0) return true;
 9         Stack<Integer> stack = new Stack<Integer>();
10         char c;
11         int temp;
12         for(int i = 0; i < s.length(); i++) {
13             c = s.charAt(i);
14             if (c == ‘(‘) stack.add(1);// store left bracket
15             else if (c == ‘[‘) stack.add(2);
16             else if (c == ‘{‘) stack.add(4);
17             else {
18                 if (stack.empty()) return false;
19                 if (c == ‘)‘) temp = -1;  //right bracket
20                 else if (c == ‘]‘) temp = -2;
21                 else temp = -4;
22                 if(stack.peek() + temp != 0) {
23                     return false; //judge
24                 } else {
25                     stack.pop();
26                 }
27             }
28         }
29         if (stack.isEmpty()) {
30             return true;
31         } else {
32             return false;
33         }
34     }
35 
36     public static void main(String args[]){
37         String s = "()(((([][[][{}{()}]])))){}[][{}]";
38 
39         System.out.println("output:  " + isValid(s));
40     }
41 }

 

Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/rustfisher/p/4862372.html

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