当前位置:网站首页>Leetcode 1249. 移除无效的括号(牛逼,终于做出来了)
Leetcode 1249. 移除无效的括号(牛逼,终于做出来了)
2022-06-25 10:55:00 【我不是萧海哇~~~~】
给你一个由 ‘(’、‘)’ 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 ‘(’ 或者 ‘)’ (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下 任意一条 要求:
空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
示例 1:
输入:s = “lee(to)de)”
输出:“lee(to)de”
解释:“lee(t(co)de)” , “lee(tode)” 也是一个可行答案。
示例 2:
输入:s = "a)b(c)d"
输出:"ab(c)d"
示例 3:
输入:s = "))(("
输出:""
解释:空字符串也是有效的
提示:
- 1 <= s.length <= 10^5
- s[i] 可能是 ‘(’、‘)’ 或英文小写字母
主要思路:自定义一个结构体,用来记录’(‘和‘)’的位置信息
然后删除有效的括号,最后剩下的就是多余的’(‘和’)',然后从原始字符串遍历,跳过这些多余的括号就是答案。
Code:
class Solution {
public:
string minRemoveToMakeValid(string s) {
typedef struct
{
char temp;
int pos;
}param;
vector<param>vec;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(' || s[i]==')')
{
param p;
p.temp=s[i];
p.pos=i;
vec.push_back(p);//记录括号信息
}
}
if(vec.size()==0)
return s;
//以下步骤是删除有效的括号
vector<param>vec2;//这个数组最后剩下的不合法的括号信息
for(int i=0;i<vec.size();i++)
{
if(vec2.size()==0)
{
vec2.push_back(vec[i]);
continue;
}
param p=vec2.back();
if(p.temp=='(')
{
if(vec[i].temp==')')
{
vec2.pop_back();
cout<<"-++"<<endl;
}
else
vec2.push_back(vec[i]);
}
else
{
vec2.push_back(vec[i]);
}
}
for(int i=0;i<vec2.size();i++)
{
cout<<vec2[i].pos<<endl;
}
int loop=0;
string res;
for(int i=0;i<s.length();i++)
{
if( (loop!=vec2.size())&& i==vec2[loop].pos )
{
loop++;
}
else
{
res+=s[i];
}
}
cout<<"res="<<res<<endl;
return res;
}
};
边栏推荐
猜你喜欢
How to start the phpstudy server
【观察】ObjectScale:重新定义下一代对象存储,戴尔科技的重构与创新
Android之Kotlin语法详解与使用
Apache ShenYu 入門
Query method and interrupt method to realize USART communication
Nuxtjs actual combat case
网易开源的分布式存储系统 Curve 正式成为 CNCF 沙箱项目
Oracle彻底卸载的完整步骤
【文件包含漏洞-03】文件包含漏洞的六种利用方式
[file inclusion vulnerability-04] classic interview question: how to getshell when a website is known to have only local file inclusion vulnerability?
随机推荐
Detailed explanation of Android interview notes handler
持续交付-Jenkinsfile 语法
Flutter adds event listening | subscription
[file inclusion vulnerability-04] classic interview question: how to getshell when a website is known to have only local file inclusion vulnerability?
Performance file system
好好思考
Android:kotlin中Gson与JSON的泛型映射解析
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-7
Query method and interrupt method to realize USART communication
MySQL and Oracle processing CLOB and blob fields
龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书
服务端渲染
Think about it
网易开源的分布式存储系统 Curve 正式成为 CNCF 沙箱项目
视频会议一体机的技术实践和发展趋势
How to start the phpstudy server
keep-alive
每日3题(3)-检查整数及其两倍数是否存在
指南针在上面开股票账户安全吗?
1-7Vmware中的快照与克隆