LeetCode -- Valid Parenthese
2024-08-23 14:46:42
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;
} }
最新文章
- 异常 java.util.regex.PatternSyntaxException:
- 找不到类型或命名空间 datarowview
- RHEL7 Ansible
- C++转换unicode utf-8 gb2312编码
- iOS中枚举定义的三种方式
- Ubuntu下访问SSH
- css中盒子宽高的auto
- Java基础知识二次学习--第七章 容器
- python学习笔记(十)、文件操作
- poi读取excel内容工具类
- Laravel表单传值
- python 全栈开发,Day53(jQuery的介绍,jQuery的选择器,jQuery动画效果)
- layui 下拉框不显示解决方法
- C#-VS发布网站-摘
- go语言之行--数组、切片、map
- kubernetes实战(十三):k8s使用helm持久化部署harbor集成openLDAP登录
- statement 对象执行sql语句
- Https自签名证书认证及数据请求的封装
- maven多层项目配置
- Lua调用C++带参数的方法
热门文章
- securecrt颜色设置
- 电话状态监听 - iOS
- Xcode 中 pch 文件配置 - iOS
- 洛谷P1829 [国家集训队]Crash的数字表格 / JZPTAB(莫比乌斯反演)
- python-读写文件的方式
- struts2属性驱动模型
- 有一段<;script>;代码,效果是点击<;p>;就会弹出信息,但是有的<;p>;点击会有效果,有的没有效果
- html基础之遗忘篇
- php 操作 mysql 实现批量执行mysql语句 mysql文件
- Linux入门篇(五)——Shell(一)