题目:有效的括号序列

难度:Easy

题目内容

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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的更多相关文章

  1. leetcode第31题--Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  3. 【LeetCode每天一题】Valid Parentheses(有效的括弧)

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  4. 乘风破浪:LeetCode真题_032_Longest Valid Parentheses

    乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...

  5. 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 + ...

  6. 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 ...

  7. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  8. 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 ...

  9. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

随机推荐

  1. oracle闪回、闪回数据归档Flashback Data Archive (Oracle Total Recall)的真正强大之处、11gR2增强以及合理使用

    oracle的闪回很早就出来了,准确的说一直以来应该都较少被真正用户广为使用,除了dba和极少部分开发人员偶尔用于逻辑出错.误删恢复之外,较少被用于产生更有价值的用途. 各种闪回表flashback ...

  2. String类的知识点(不断更新)

    知识点1.String类位于java.lang包中,具有丰富的方法计算字符串的长度.比较字符串.连接字符串.提取字符串2.数组的length是属性,字符串的length()是方法3.import ja ...

  3. http请求记录

    Request Headers 请求头 Content-Type 默认值: "application/x-www-form-urlencoded".发送信息至服务器时内容编码类型 ...

  4. [c/c++] programming之路(10)、格式符后续

    一.格式符 1. f格式符 #include<stdio.h> #include<stdlib.h> void main(){ printf("%f",10 ...

  5. 【Python029--一个任务】

    一.文件编写 任务:将文件(record.txt)中的数据进行分割,并按照以下规律保存起来: --小甲鱼的对话单独保存为boy_*.txt的文件(去掉“小甲鱼:”) --小客服的对话单独保存为girl ...

  6. uniGUI试用笔记(十)

    今天用LoadRunner对uniGUI的Standalone模式的程序进行了一次压力测试,程序采用三层模式,将应用服务器与Web服务器分离,由于条件限制,数据库.应用服务和Web服务都部署在同一条云 ...

  7. Linux内核中的netlink是什么?

    答: 是一种内核与用户应用间的双向数据传输方式,用户态使用传统的socketAPI即可使用netlink提供的功能,但是内核态需要使用专门的api来使用netlink.

  8. cmd使用管理员权限运行,启动路径不是当前目录

    https://stackoverflow.com/questions/672693/windows-batch-file-starting-directory-when-run-as-admin B ...

  9. P2473 [SCOI2008]奖励关

    思路 n<=15,所以状压 因为求期望,所以采用逆推的思路,设\(f[i][S]\)表示1~i的宝物获得情况是S,i+1~k的期望 状态转移是当k可以取时,\(f[i][S]+=max(f[i+ ...

  10. [CodeForces 892A] Greed (Java中sort实现从大到小排序)

    题目链接:http://codeforces.com/problemset/problem/892/A 具体的Java 中 sort实现降序排序:https://www.cnblogs.com/you ...