20. Valid Parentheses

错误解法:

"[])"就会报错,没考虑到出现')'、']'、'}'时,stack为空的情况,这种情况也无法匹配

class Solution {
public:
bool isValid(string s) {
if(s.empty())
return false;
stack<char> st;
st.push(s[]);
for(int i = ;i < s.size();i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
st.push(s[i]);
else if(s[i] == ')'){
if(st.top() == '(')
st.pop();
else
return false;
}
else if(s[i] == ']'){
if(st.top() == '[')
st.pop();
else
return false;
}
else if(s[i] == '}'){
if(st.top() == '{')
st.pop();
else
return false;
}
}
return st.empty() ? true : false;
}
};

正确解法:

class Solution {
public:
bool isValid(string s) {
int length = s.size();
if(length < )
return false;
stack<char> result;
for(int i = ;i < length;i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
result.push(s[i]);
else{
if(result.empty())
return false;
if(s[i] == ')' && result.top() != '(')
return false;
if(s[i] == ']' && result.top() != '[')
return false;
if(s[i] == '}' && result.top() != '{')
return false;
result.pop();
}
}
return result.empty();
}
};

32. Longest Valid Parentheses

https://www.cnblogs.com/grandyang/p/4424731.html

这个题求的是最长的连续匹配正确的符号。

匹配错误只可能是右括号')'存在时,堆中没有左括号'('进行匹配。start用来继续这个连续匹配的开始位置,只有在匹配错误的情况下,这个start才更新。

如果匹配成功后,堆中没有左括号'(',则说明从start到当前都是匹配正确了的;

注意必须用i - position.top(),可能出现这种情况'(()()',如果你使用i - position弹出的那个位置,你永远只可能获得长度为2的,不可能获得连续的长度。

class Solution {
public:
int longestValidParentheses(string s) {
int start = ,res = ;
stack<int> position;
for(int i = ;i < s.size();i++){
if(s[i] == '(')
position.push(i);
else if(s[i] == ')'){
if(position.empty())
start = i + ;
else{
position.pop();
res = position.empty() ? max(res,i - start + ) : max(res,i - position.top());
}
}
}
return res;
}
};

自己写的一个版本,更容易理解:

class Solution {
public:
int longestValidParentheses(string s) {
stack<int> sta;
int res = ;
int left = -;
for(int i = ;i < s.size();i++){
if(s[i] == '(')
sta.push(i);
else{
if(sta.empty())
left = i;
else{
int index = sta.top();
sta.pop();
if(sta.empty())
res = max(res,i - left);
else
res = max(res,i - sta.top());
}
}
}
return res;
}
};

301. Remove Invalid Parentheses

这个题是求删除后所有合法的,并且要求删除次数必须最少。

这个题与前面两个题稍稍有点不同,这个题需要用bfs的方式,把每个位置的字符删除加入队列判断是否合法,一旦有合法的就不再进行删除操作,而是把队列中剩下的进行判断是否合法就行了。

使用了visited数组,这样防止了搜索的重复计算

class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> res;
unordered_set<string> visited;
visited.insert(s);
queue<string> q;
q.push(s);
bool finished = false;
while(!q.empty()){
string tmp = q.front();
q.pop();
if(isValid(tmp)){
res.push_back(tmp);
finished = true;
}
if(finished)
continue;
for(int i = ;i < tmp.size();i++){
if(tmp[i] != '(' && tmp[i] != ')')
continue;
string t = tmp.substr(,i) + tmp.substr(i+);
if(!visited.count(t)){
visited.insert(t);
q.push(t);
}
}
}
return res;
}
bool isValid(string s){
int count = ;
for(int i = ;i < s.size();i++){
if(s[i] != '(' && s[i] != ')')
continue;
else if(s[i] == '(')
count++;
else{
if(count <= )
return false;
else
count--;
}
}
return count == ;
}
};

leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、的更多相关文章

  1. [Leetcode][Python]32: Longest Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...

  2. 刷题32. Longest Valid Parentheses

    一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过 ...

  3. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

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

  4. 【一天一道LeetCode】#32. Longest Valid Parentheses

    一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...

  5. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  6. leetcode 32. Longest Valid Parentheses

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

  7. Java [leetcode 32]Longest Valid Parentheses

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

  8. leetcode problem 32 -- Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  9. [leetcode]32. Longest Valid Parentheses最长合法括号子串

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

随机推荐

  1. Vue动态新增对象属性

    Vue.set( target, key, value ) 参数: {Object | Array} target {string | number} key {any} value 返回值:设置的值 ...

  2. 大数据之 Spark

    1 渊源 于2009由Matei Zaharia创立了spark大数据处理和计算框架,基于内存,用scala编写. 2 部署 2.1 需要软件包 下载路径见已有博文 Jdk ——因为运行环境为jvm ...

  3. Linux常用基本命令:三剑客命令之-awk动作用法(1)

    1,多个动作,怎么写? ghostwu@dev:~/linux/awk$ cat host.txt name ip地址 host1 192.168.1.1 host2 192.177.81.1 hos ...

  4. 百度地图坐标偏移,微信小程序地图偏移问题,腾讯地图坐标偏移

    解决方案: 如果用百度的地图获取的坐标点,在微信小程序内使用,就会出现偏移 算法(lat和lng是经纬度,球面坐标): To_B是转到百度,To_G是转到GCJ-02(谷歌,高德,腾讯) var TO ...

  5. 洛谷P4438 [HNOI/AHOI2018]道路(dp)

    题意 题目链接 Sol 每当出题人想起他出的HNOI 2018 Day2T3,他都会激动的拍打着轮椅 读题比做题用时长系列... \(f[i][a][b]\)表示从根到\(i\)的路径上,有\(a\) ...

  6. 【代码笔记】Web-HTML-框架

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  7. SuperMap 三维产品资料一览表

    转自:http://blog.csdn.net/supermapsupport/article/details/68924713 如何能快速地开发项目中的三维功能呢?本文为您提供全方位的三维资料,为您 ...

  8. Android、IOS文字居中偏离的解决方案

    前言 移动端开发,经常会遇到的问题,就是文字居中.一般都只能往css方向去fix这个问题. 自己以前也用过position:relative;top:-*px的方式去解决.

  9. 洗礼灵魂,修炼python(15)--列表进阶话题—>列表解析/列表生成器

    是的,我是想到什么知识点就说什么,没有固定的主题,我的标题都是在写完博客再给的.本篇博文说说列表进阶话题.其实列表应该是比较熟悉的了,而毫不夸张的说,在实际的开发中,列表也是使用的最多的,以后你会体会 ...

  10. EntityFramework Code-First 简易教程(五)-------领域类配置

    前言:在前篇中,总是把领域类(Domain Class)翻译成模型类,因为我的理解它就是一个现实对象的抽象模型,不知道对不对.以防止将来可能的歧义,这篇开始还是直接对Domain Class直译. 前 ...