LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列
难度:Easy
题目内容:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
翻译:给定一个字符串,只包含字符'(',')','{ ','}','['和']',确定输入字符串是否有效。
输入字符串是有效的:
开括号必须以相同类型的括号关闭。
打开括号必须以正确的顺序关闭。
注意,空字符串也被认为是有效的。
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
我的思路:数据结构——括号问题是经典的栈问题。
【因为这有三种括号,三个之间的嵌套比较复杂,所以不能简单地使用整形int作为判断(左括号++,右括号--),例如“([)]”这要是使用int那么就会判断正确。】
算法——利用一个栈,如果是左括号则直接放入,如果是右括号,pop栈顶看是否为对应左括号,否则return false;最后检查栈是否为空。
我的代码:
public boolean isValid(String s) {
char[] sc = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i<s.length(); i++) {
switch (sc[i]) {
case ')':
if (stack.empty() || stack.pop() != '(')
return false;
break;
case '}':
if (stack.empty() || stack.pop() != '{')
return false;
break;
case ']':
if (stack.empty() || stack.pop() != '[')
return false;
break;
default:
stack.push(sc[i]);
}
}
return stack.empty();
}
我的算法复杂度:时间——O(N) 空间——O(N)
编码过程出现问题:
1、一开始用的if else 比较繁琐,后来改的switch; 对于先peek判断再pop的,可以直接优化为判断相反条件的pop
例如:
if (!stack.empty() && stack.peek() == '[')
stack.pop();
else
return false;
break;
可以优化成:
if (stack.empty() || stack.pop() != '[')
return false;
break;
【其实没什么卵用。。】
2、pop()之前应该要判断栈是否为空,如果为空,也应该return false;
3、其实最开始可以加一个判断,如果s的长度为单数,则直接返回false。
参考答案代码:
public boolean isValid(String s) {
if ((s.length() & 1) == 1)
return false;
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
答案算法复杂度:时间——O(N) 空间——O(N)
答案思想:其实思想和我的那个差不多【强行不要脸】,不过这个方法利用了反向思维:如果当前是左括号,则放入对应的右括号,如果是右括号则pop栈顶是否是“自己”,否则return false。这样一来就减少了代码里对是否是对应左括号的判断。不过两者算法复杂度和意义上都一样,一个可读性好些,一个更加简练一些。
LeetCode第[20]题(Java):Valid Parentheses的更多相关文章
- leetcode第31题--Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- LeetCode专题-Python实现之第20题:Valid Parentheses
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- 【LeetCode每天一题】Valid Parentheses(有效的括弧)
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 乘风破浪:LeetCode真题_032_Longest Valid Parentheses
乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...
- LeetCode第[18]题(Java):4Sum 标签:Array
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...
- LeetCode第[1]题(Java):Two Sum 标签:Array
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
随机推荐
- Net中应用 Redis 扩展类
GIt地址:https://gitee.com/loogn/stackexchange-redis-typedextensions 1.stackexchange 类调用 using System; ...
- 2018-2019-2 《网络对抗技术》Exp4 恶意代码分析20165211
目录 实践内容概述 实践目标 实践内容 实验问题回答 实践过程记录 系统运行监控 使用schtacks指令监控系统运行 使用sysmon工具监控系统运行 恶意软件分析 使用Virus Total分析恶 ...
- luogu 3790 文艺数学题 - 矩阵树定理 - 容斥原理
题目传送门 戳我来传送 题目大意 给定一个图,问它的所有生成树的边权的最大公约数之和. 可以考虑计算边权的最大公约数为$i$的生成树的个数$f(i)$,最后累加答案. 然后考虑这样的生成树的个数怎么求 ...
- 如何使用AsyncTask
1 如何使用handler,安卓规定只能再UI线程里面刷新UI,但是不能再UI线程里面执行耗时操作.所以我们要把耗时操作放在子线程里,然后把要刷新UI的操作传递到handler里面,然后在由Handl ...
- 鼠标滑轮事件QWheelEvent
一般鼠标滑轮事件会发出信号,参数是QWheelEvent,只需要新建槽函数,QWheelEvent作为参数. void myMouseWheelEvent(QWheelEvent* even) {)/ ...
- 4514: [Sdoi2016]数字配对 费用流
链接 https://www.lydsy.com/JudgeOnline/problem.php?id=4514 思路 EK直接贪心做 <0的时候加上剩余返回 二分图a->b的时候 把b- ...
- 【做题】spoj4060 A game with probability——dp
赛前做题时忽然发现自己概率博弈类dp很弱,心好慌.(获胜概率或最优解期望) 于是就做了这道题,续了特别久. 一开始列dp式子的时候就花了很长时间,首先搞错了两次,然后忘记了根据上一轮dp值直接确定选什 ...
- LuoguP2161 [SHOI2009]会场预约
题目地址 题目链接 题解 用fhqtreap对区间进行维护. 可以注意到的是,对于当前存在的预约,他们一定是升序排列的(有重叠的都被删了). 那么就可以用按照位置分裂的fhqtreap搞了(预约无论按 ...
- ES6模块化操作
在ES5中我们要进行模块化操作需要引入第三方类库,随着前后端分离,前端的业务日渐复杂,ES6为我们增加了模块化操作.模块化操作主要包括两个方面. export :负责进行模块化,也是模块的输出. im ...
- Images之base image
Create a base image Most Dockerfiles start from a parent image. If you need to completely control th ...