题目:有效的括号序列

难度: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. android样式之按钮&&图片

    在drawable-hdpi中添加xml文件 <?xml version="1.0" encoding="utf-8"?> <selector ...

  2. python简说(二十九)线程,进程

    进程: 一些资源的集合. 一个进程里面最少有一个线程,主线程.线程: 程序执行的最小单位. import threadingfrom threading import Threadimport tim ...

  3. oracle基础——内存管理、优化

    内存图解: 自动管理:11g:AMM   10g:ASMM SGA(system global area):由所有服务进程和后台进程共享 PGA(program global area): 由每个服务 ...

  4. (4运行例子)自己动手,编写神经网络程序,解决Mnist问题,并网络化部署

    ​1.联通ColaB 2.运行最基础mnist例子,并且打印图表结果  # https://pypi.python.org/pypi/pydot#!apt-get -qq install -y gra ...

  5. Vue父子组件生命周期

    转载自:https://blog.csdn.net/a8725585/article/details/79092505 vue父子组件钩子函数触发顺序 beforeMount后mounted前构造子组 ...

  6. QWidget设置背景图

    1.使用QSS出现很多问题 2.方法 this->setAutoFillBackground(true); QPalette palette = this->palette(); pale ...

  7. Junit中AssertTrue的使用

    assertTrue public static void assertTrue(String message, boolean condition) Asserts that a condition ...

  8. topcoder srm 702 div1 -3

    1.给定一个$n*m$的矩阵,里面的数字是1到$n*m$的一个排列.一个$n*m$矩阵$A$对应一个$n*m$ 的01字符串,字符串的位置$i*m+j$为1当且仅当$A_{i,j}=i*m+j+1$. ...

  9. 新建一个Windows Service的方法

    http://www.cnblogs.com/YanPSun/archive/2010/05/22/1741381.html http://blog.csdn.net/m15188153014/art ...

  10. Python3 tkinter基础 Canvas create_line 画实线与虚线

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...