leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、
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 、的更多相关文章
- [Leetcode][Python]32: Longest Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...
- 刷题32. Longest Valid Parentheses
一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过 ...
- [LeetCode] 32. Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【一天一道LeetCode】#32. Longest Valid Parentheses
一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...
- leetcode解题报告 32. Longest Valid Parentheses 用stack的解法
第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...
- leetcode 32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Java [leetcode 32]Longest Valid Parentheses
题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...
- leetcode problem 32 -- Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- [leetcode]32. Longest Valid Parentheses最长合法括号子串
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
随机推荐
- angularjs学习第五天笔记(第二篇:表单验证升级篇)
您好,我是一名后端开发工程师,由于工作需要,现在系统的从0开始学习前端js框架之angular,每天把学习的一些心得分享出来,如果有什么说的不对的地方,请多多指正,多多包涵我这个前端菜鸟,欢迎大家的点 ...
- c# 后台拼接分页Html
public static string ReplaceStr(string originalStr, string oldStr, string newStr) { if (string.IsNul ...
- [Python] Python基础字符串
Python的语法采用缩进的方式,一般使用四个空格,并且是大小写敏感的 字符编码 计算机只能处理数字,如果要处理文本,必须先把文本转换成数字才能处理 采用8个比特(bit)作为一个字节(byte) 一 ...
- vue VNode如何使用,是什么东西?
前言:element ui 中有些 demo 使用了 vue 的 VNode,但是 demo 毕竟不全,所以想要了解 VNode 到底是什么,如何写出符合自己业务的代码. vue 官网介绍:渲染函数 ...
- callback.js
function writeCode(callback){ console.log("i am waiting....") callback(); console.log(&quo ...
- 在 Ubuntu 18.04 下安装 fcitx 及搜狗拼音输入法
感觉自己傻逼透了,之前在 16.04 时折腾着要装 ibus 和 rime 输入法,现在 18.04 默认安装 ibus 了,又因为 rime 的智能联想太弱,打字不爽,又想装回搜狗一劳永逸... 环 ...
- python小练习:用户三次登陆, 购物车
2018.12.1 周末练习: 1.用户三次登陆 from random import randint i = 1 while i < 4: num = 0 verify_code = '' w ...
- form的重置reset
HTML中Form表单的reset方法被用来重置用户所输入的内容,以前一直误以为其是单纯的将input等输入项中的值清空. 但实际上不是这样的,reset方法的本质是将input等输入项中的内容还原为 ...
- windows 2012 r2企业版没有界面
windows 2012 R2系统进去以后只有CMD命令窗口,没有图形化界面,除了cmd其余的全部是黑的.在网上搜了很多,都是大同小异的解决方法,但根本解决不了.今天再这里分享的这个方法很简单,不用重 ...
- 遇到了ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
解决方法如下: 1. 通过命令查找libmysqlclient_r.so.16 在什么地方,一般是在/usr/lib64/mysql/下面 2. 做一个链接到/usr/lib64 下: ln -s / ...