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 ( ...
随机推荐
- MySQL按指定字段自定义列表排序
亲测实例: 1级排序:同城>异城 2级排序:未领养>以领养 3级排序:发布最新靠前 MYSQL语句如下: SELECT ura.id,ura.city,ura.uid,ura.rescue ...
- DGUT_FLY退役贴 && FunCfans毕业总结-竞赛篇
严格来说我们飞跃队是去年ECFinal之后就退役的,只是这几个月有一堆事情在那,考研的考研,求职的求职,都把博客晾一边了.现在,总算能写点东西了. 我与ACM-ICPC的结缘,是从大一开学1个多月后开 ...
- 关于typeid和typeof
typeid和typeof是c++/gcc编译器的两个关键字,也就是操作符,所以他们根本就不会声明在头文件中. 只不过typeid返回的是type_info,它定义在<typeinfo>头 ...
- jackson JsonPropertyOrder和@JsonIgnoreProperties注解
有些时候,我们在和外部系统交互的时候使用了json作为标准的数据交换格式,同时为了安全性考虑,增加了对报文的校验,因此我们需要确保序列化的时候参数有序且不多不少刚好,因为对外的API不像后台和前端交互 ...
- vue 起步
vue 官网 目前最火的前端框架当属Vue.js了,很多使用过vue的程序员这样评价它,“vue.js兼具angular.js和react.js的优点,并剔除了它们的缺点”.授予了这么高的评价的vue ...
- 单片机中printf函数的重映射
单片机中printf函数的重映射 一.源自于:大侠有话说 1.如果你在学习单片机之前学过C语言,那么一定知道printf这个函数.它最最好用的功能 除了打印你想要的字符到屏幕上外,还能把数字进行格式化 ...
- MVC 之 初识(一)
创建一个mvc项目,在项目中会startup.cs文件,startup文件主要是将项目寻找一个宿主 过去,项目一般都是寄宿在iis上的,通过owin可以寄宿到不同的宿主. 可以关闭owin:<a ...
- P3727 曼哈顿计划E
点分治+SG函数还真是令人意外的组合啊 思路 这道题看到找一条满足条件的链,想到点分治 看到博弈,想到SG函数 然后就变成一道SG函数+点分治的题了 然后1e9的SG函数怎么搞?当然是打表了 然后各种 ...
- Joint Detection and Identification Feature Learning for Person Search
Joint Detection and Identification Feature Learning for Person Search 2018-06-02 本文的贡献主要体现在: 提出一种联合的 ...
- Hierarchical Question-Image Co-Attention for Visual Question Answering
Hierarchical Question-Image Co-Attention for Visual Question Answering NIPS 2016 Paper: https://arxi ...