码迷,mamicode.com
首页 > 编程语言 > 详细

20. Valid Parentheses java solutions

时间:2016-05-16 12:37:58      阅读:143      评论: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.

 

Subscribe to see which companies asked this question

 

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         if(s == null || s.length() == 0) return false;
 4         Stack<Character> stack = new Stack<Character>();
 5         for(int i = 0; i< s.length(); i++){
 6             if(!stack.empty()){
 7                 if(s.charAt(i) == ‘)‘ && stack.peek() == ‘(‘)
 8                     stack.pop();
 9                 else if(s.charAt(i) == ‘]‘ && stack.peek() == ‘[‘)
10                     stack.pop();
11                 else if(s.charAt(i) == ‘}‘ && stack.peek() == ‘{‘)
12                     stack.pop();
13                 else
14                     stack.push(s.charAt(i));
15             }else
16                 stack.push(s.charAt(i));
17         }
18         return stack.empty();
19     }
20 }

 

20. Valid Parentheses java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5497411.html

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