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 ( ...
随机推荐
- curl 抓取图片
/** * curl 抓取图片 * @param $url * @return mixed */ public static function downLoadImage($url) { $heade ...
- P1384 幸运数与排列
P1384 幸运数与排列 神奇的(逆)康托展开:求1到n的全排列中字典序第k小的排列 $k<=10^9<13!$,显然$k$最多只会影响后$13$位 前面一大串都是有序从小到大排列的,于是 ...
- Solr索引配置
Solr主配置文件 schema.xml,在SolrCore的conf目录下,它是Solr数据表配置文件,它定义了加入索引的数据的数据类型的.主要包括FieldTypes.Fields和其他的一些缺省 ...
- glibc 2.x release note
glibc 2.x release note,参见: https://sourceware.org/glibc/wiki/Glibc%20Timeline https://www.gnu.org/so ...
- 20145212 罗天晨 WEB登陆发贴及会话管理功能的实现
会话管理简介 Cookie: cookie常用于识别用户. cookie 是服务器留在用户计算机中的小文件,每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie. 通过PHP能够创建并取回 ...
- linux中没有tree命令,command not found,解决办法
在有网络的情况下: 1.包管理器安装 centos 中用 yum -y install tree ubuntu 中用 apt-get install tree 当然如果需要权限不要忘了在前面加上 ...
- poj 3687 Labeling Balls - 贪心 - 拓扑排序
Windy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 to N ...
- noip 2013 提高组 day1
1.转圈游戏: 解析部分略,快速幂就可以过 Code: #include<iostream> #include<fstream> using namespace std; if ...
- vi中如何使用cscope来查找函数的定义
答:进入命令行模式输入:cs f g <function_name>
- Manjaro 系统添加国内源和安装搜狗输入法
添加中科大源 #打开配置文件 kate /etc/pacman.conf 在文件末尾添加 [archlinuxcn] SigLevel = Optional TrustedOnly Server = ...