Question:

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.

Analysis:

问题描述:给出一个字符串,包含'('')''{''}''[' and ']'确定它是否是有效地匹配括号。

思路:一看到括号匹配问题肯定想到用栈。遇到左括号就进栈;遇到右括号若栈顶元素与之匹配则POP出栈顶元素,若不匹配则返回false。

注意特殊情况:如"{}[]()", 或者“{[}]”, 或者“{{}}{{”等情况。

Answer:

public class Solution {
public boolean isValid(String s) {
char[] ch = s.toCharArray();
int n = ch.length;
if(ch.length == 0 || ch.length % 2 != 0)
return false;
if(ch[0] == '}' || ch[0] == ']' || ch[0] == ')')
return false;
Stack<Character> st = new Stack<Character>();
st.add(ch[0]);
int i = 1;
while(!st.isEmpty() && i < n) {
if(ch[i] == '{' || ch[i] == '[' || ch[i] == '(') {
st.add(ch[i]);
i++;
} else {
if(st.isEmpty())
return false;
char c = st.pop();
if(c == '{' && ch[i] != '}' || c == '[' && ch[i] != ']'
|| c == '(' && ch[i] != ')')
return false;
i++;
if(i < n && (ch[i] == '{' || ch[i] == '[' || ch[i] == '(')) {
st.add(ch[i]);
i++;
}
}
}
System.out.println(i +" " +st.size());
if(!st.isEmpty() || i < n - 1)
return false; return true;
} }

最新文章

  1. 异常 java.util.regex.PatternSyntaxException:
  2. 找不到类型或命名空间 datarowview
  3. RHEL7 Ansible
  4. C++转换unicode utf-8 gb2312编码
  5. iOS中枚举定义的三种方式
  6. Ubuntu下访问SSH
  7. css中盒子宽高的auto
  8. Java基础知识二次学习--第七章 容器
  9. python学习笔记(十)、文件操作
  10. poi读取excel内容工具类
  11. Laravel表单传值
  12. python 全栈开发,Day53(jQuery的介绍,jQuery的选择器,jQuery动画效果)
  13. layui 下拉框不显示解决方法
  14. C#-VS发布网站-摘
  15. go语言之行--数组、切片、map
  16. kubernetes实战(十三):k8s使用helm持久化部署harbor集成openLDAP登录
  17. statement 对象执行sql语句
  18. Https自签名证书认证及数据请求的封装
  19. maven多层项目配置
  20. Lua调用C++带参数的方法

热门文章

  1. securecrt颜色设置
  2. 电话状态监听 - iOS
  3. Xcode 中 pch 文件配置 - iOS
  4. 洛谷P1829 [国家集训队]Crash的数字表格 / JZPTAB(莫比乌斯反演)
  5. python-读写文件的方式
  6. struts2属性驱动模型
  7. 有一段&lt;script&gt;代码,效果是点击&lt;p&gt;就会弹出信息,但是有的&lt;p&gt;点击会有效果,有的没有效果
  8. html基础之遗忘篇
  9. php 操作 mysql 实现批量执行mysql语句 mysql文件
  10. Linux入门篇(五)——Shell(一)