Chinaunix首页 | 论坛 | 博客
  • 博客访问: 254197
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-04-02 19:08:54


import java.util.HashMap;
import java.util.Map;
import java.util.Stack;


//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.
public class ValidParentheses {
 public boolean isValid(String s) {
 if(s==null||s.length()==0)
 return true;
      Map map=new HashMap();
  map.put('{', '}');
  map.put('[', ']');
  map.put('(', ')');
  Stack stack=new Stack();
  for(int i=0;i   char cur=s.charAt(i);
  if(map.keySet().contains(cur))
  stack.add(s.charAt(i));
  else if(map.values().contains(cur)){
  if(!stack.empty()&&cur==map.get(stack.peek())){
  stack.pop();
  }
  else {
return false;
}
  
  }
  }
  //注意stack空了才能是对的
  return stack.empty();
 
      
 }
}

Valid Parentheses
阅读(698) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~