LeetCode记录之20——Valid Parentheses
09.18更新算法采用栈的思想解决,方法①所示。
本题主要是找是否有匹配的字符串,因为还没有复习到栈之类的知识点,只能还是采用暴力方法了,后期会补上更加优化的算法。我的思路就是先遍历一遍找是否有匹配的符号,有的话就删除,然后继续遍历,直至结束。
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
给定一个字符串,只包含字符“(”、“””、“{”、“}”、“[”和“”),确定输入字符串是否有效。
括号必须以正确的顺序关闭,“()”和“()”{“}”都是有效的,但“()和[([ ] ] ] ]不是。
①利用栈的思想进行解决。
/*
* 利用栈来进行平衡符号的匹配。
* {[(三种符号是开放字符,)]}是封闭符号。
* 当前字符为开放符号时,入栈。当为封闭符号时,出栈,并与出栈元素进行匹配。
* 当循环结束时,栈为空即所有符号都进行匹配,配对成功。
* */
public boolean isValid(String s){
Stack<Character> chars=new Stack<>();
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
switch (ch) {
case '(':
chars.push(ch);
break;
case ')':
if(chars.empty())
return false;
else {
char getCh=chars.pop();
if(!(getCh=='('))
return false;
}
break;
case '[':
chars.push(ch);
break;
case ']':
if(chars.empty())
return false;
else {
char getCh=chars.pop();
if(!(getCh=='['))
return false;
}
break;
case '{':
chars.push(ch);
break;
case '}':
if(chars.empty())
return false;
else {
char getCh=chars.pop();
if(!(getCh=='{'))
return false;
}
break;
default:
break;
}
}
if(chars.isEmpty())
return true;
else
return false;
}
②利用暴力方式进行解决(不推荐)
public boolean isValid(String s){
int length=s.length();
boolean isDelete=false;
if(length==0||length%2!=0)//判断字符串是否为空或者无法匹配
return false;
while (length >0) {
for (int i = 0; i < length - 1; i++) {
if ((s.charAt(i) == '(' && s.charAt(i + 1) == ')') || (s.charAt(i) == '{' && s.charAt(i + 1) == '}')
|| (s.charAt(i) == '[' && s.charAt(i + 1) == ']')) {
if(i+2!=length)
s = s.substring(0, i) + s.substring(i + 2, length);//非最后两位字符串截取
else
s = s.substring(0, i);//最后两位字符串截取
length -= 2;//字符串长度减2
isDelete=true;
i=0;//每次将基数归零重新循环
}
else
isDelete=false;//如果循环一次没有任何匹配直接返回false
}
if (!isDelete)
return false;
}
return true;
}
LeetCode记录之20——Valid Parentheses的更多相关文章
- LeetCode解题笔记 - 20. Valid Parentheses
这星期听别人说在做LeetCode,让他分享一题来看看.试了感觉挺有意思,可以培养自己的思路,还能方便的查看优秀的解决方案.准备自己也开始. 解决方案通常有多种多样,我觉得把自己的解决思路记录下来,阶 ...
- leetCode练题——20. Valid Parentheses
1.题目 20. Valid Parentheses——Easy Given a string containing just the characters '(', ')', '{', '}', ...
- <LeetCode OJ> 20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 【leetcode❤python】 20. Valid Parentheses
#-*- coding: UTF-8 -*-#利用栈的思想#如果输入的左测扩则入栈,如果输入为右侧扩,判断其是否与当前栈顶配对,如果匹配则删除这一对,否则return False#'(', ')', ...
- leetcode个人题解——#20 Valid Parentheses
class Solution { public: bool isValid(string s) { stack<char> brackts; ; i < s.size(); i++) ...
- [Leetcode][Python]20: Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...
- 20. Valid Parentheses【leetcode】
20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...
- leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、
20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
随机推荐
- memcache 加载(对象)所遇到的问题。资源
<?php $mem =new memcache(); if($mem->connect('127.0.0.1','11211')){ echo '连接OK'.'<br>'; ...
- 线程dump
当应用程序运行变慢或者发生故障时,可能通过分析java的Thread Dumps得到分析他们得到阻塞和存在瓶颈的线程. 线程堆栈是虚拟机中线程(包括锁)状态的一个瞬间状态的快照,即系统在某一个时刻所有 ...
- SpringBoot27 JDK动态代理详解、获取指定的类类型、动态注册Bean、接口调用框架
1 JDK动态代理详解 静态代理.JDK动态代理.Cglib动态代理的简单实现方式和区别请参见我的另外一篇博文. 1.1 JDK代理的基本步骤 >通过实现InvocationHandler接口来 ...
- CompositePattern(23种设计模式之一)
设计模式六大原则(1):单一职责原则 设计模式六大原则(2):里氏替换原则 设计模式六大原则(3):依赖倒置原则 设计模式六大原则(4):接口隔离原则 设计模式六大原则(5):迪米特法则 设计模式六大 ...
- Luogu 2573 [SCOI2012]滑雪
BZOJ 2753 首先可以按照题目要求的把所有的有向边建出来,然后进去广搜就可以求出第一问的解,然后考虑如何求解第二问,我们把所有搜到的边按照到达的点的高度位第一关键字,边的长度为第二关键字排序之后 ...
- Luogu 3594 [POI2015]WIL-Wilcze doły
简单题. 考虑没有修改数字的条件的限制,我们直接用双指针扫描就可以计算出答案了. 然后考虑加入修改数字的条件,只要用单调队列维护出当前两个指针表示的区间中长度为$d$的一段区间的最大值,用总和减掉这个 ...
- $.post()参数及返回值
JQuery中的$.post()函数 先看一个例子:$.post("adduser.ashx", { "name": name, "sex" ...
- VS2013中全局属性与局部属性的设置
为了更好的体现程序与库的独立性,vc++2013 中库路径设置不再采用全局设置,就是说在每个工程中都可以有自己独立的库路径设置,当然你如果不设置,那默认就是vs2013自己的库路径.但是如果你需要用到 ...
- .Net插入大批量数据
1. 使用SqlDataAdapter /// <summary> /// 实现数据库事务,大批量新增数据 /// </summary> ...
- redis内存优化方法
先来认识2个redis配置参数 hash-max-ziplist-entries : hash内部编码压缩列表的最大值,默认512 hash-max-zipmap-value : hash内部编码压缩 ...