题目:有效的括号序列

难度: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. Docker学习笔记之通过 Dockerfile 创建镜像

    0x00 概述 由于 Docker 镜像的结构优势,使它的占用空间远小于普通的虚拟机镜像,而这就大幅减少了 Docker 镜像在网络或者其他介质中转移所花费的时间,进而提高了我们进行迁移部署的效率.不 ...

  2. JVM的垃圾回收机制

    JVM的垃圾回收机制:(GC通过确定对象是否被活动对象引用来确定是否收集该对象.) 1.触发GC(Garbage Collector)的条件. (1.GC在优先级最低的线程中运行,在未运行的线程中进行 ...

  3. jbpm 6 vs activities 5评估(持续更新、亲测实际项目评估)

    最近我们有个使用了jbpm 6.2(6.2是一个较大的里程碑)的批处理模块,因为大BOSS一直觉得太重了,希望有更加轻量级的解决方案,因为我们基本上没有真正意义上流程的概念,只有静态的流程图,因为一直 ...

  4. PHP命名空间(Namespace)的使用简介

    原文链接:https://www.cnblogs.com/zhouguowei/p/5200878.html 可以导入命名空间也可以导入命名空间的类 <?php namespace Blog\A ...

  5. CTF-逆向工程实验吧Just Click

    题目链接:http://www.shiyanbar.com/ctf/1889 步骤一:PEID解析:如下图所示 步骤二:打开exe,这种类型的东西用OD打不开,想了一下,这种东西应该是C#做的,用.n ...

  6. Windows Installation

    If you're running on Windows it is good to run Jenkins as a service so it starts up automatically wi ...

  7. error和exception有什么区别?

    Error(错误)表示系统级的错误和程序不必处理的异常,是java运行环境中的内部错误或者硬件问题.比如:内存资源不足等.对于这种错误,程序基本无能为力,除了退出运行外别无选择,它是由Java虚拟机抛 ...

  8. Docker 入门指南——部署常用服务示例

    MongoDB FROM centos:centos7 MAINTAINER The CentOS Project <cloud-ops@centos.org> RUN yum -y up ...

  9. 【基本知识】Flume基本环境搭建以及原理

    系统:CentOS6.5JDK:1.8.0_144Flume:flume-ng-1.6.0-cdh5.12.0 一.什么是Flume flume 作为 cloudera 开发的实时日志收集系统,受到了 ...

  10. IDEA新建一个Project和Module的问题