当前位置:网站首页>13 -- 移除无效的括号
13 -- 移除无效的括号
2022-06-24 06:56:00 【JH_Cao】
移除无效的括号
- 思路
- 遇到"("入栈
- 遇到")“,看栈是否为空,栈为空,则删除当前元素
栈不为空,则拿出栈顶元素进行比较
如果栈顶元素能凑成一对”()",则移除栈顶元素 - 遍历完成后,再看栈中的元素
- 存储栈的时候,用字典来存储,这样可以记录索引
- 删除的时候,从后往前删除,不要破坏索引的结构
class facebook_01 {
//s = "lee(t(c)o)de)" // "a)b(c)d" //"(a(b(c)d)" //"())()(((" "()"
//"())()((("
func minRemoveToMakeValid(_ s: String) -> String {
var arr = Array(s).map{
String($0)}
var stack = [[Int: String]]()
var left = 0
while left < arr.count {
if stack.isEmpty {
if arr[left] == ")" {
arr.remove(at: left)
} else {
if arr[left] == "(" {
let dict = [left: "("]
stack.append(dict)
}
left += 1
}
} else {
// 栈非空,取出栈顶元素进行匹配,能匹配上,就删除
let topEle = stack[stack.count - 1]
if topEle.first!.value == "(" && arr[left] == ")" {
stack.removeLast()
}
if arr[left] == "(" {
let dict = [left: "("]
stack.append(dict)
}
left += 1
}
}
if !stack.isEmpty {
for i in (0..<stack.count).reversed() {
arr.remove(at: stack[i].first!.key)
}
}
return arr.reduce("", +)
}
}
边栏推荐
- More appropriate development mode under epidemic situation
- Teach you how to use the reflect package to parse the structure of go - step 1: parameter type check
- [introduction to point cloud dataset]
- 快速读论文----AD-GCL:Adversarial Graph Augmentation to Improve Graph Contrastive Learning
- [ACNOI2022]做过也不会
- 模型效果优化,试一下多种交叉验证的方法(系统实操)
- 5g industrial router Gigabit high speed low delay
- Leetcode 515 find the leetcode path of the maximum [bfs binary tree] heroding in each row
- All you know is the test pyramid?
- Oracle advanced SQL qualified query
猜你喜欢

软件工程导论——第二章——可行性研究

Configure your own free Internet domain name with ngrok

Vulnhub靶机:BOREDHACKERBLOG_ CLOUD AV

Swift 基础 闭包/Block的使用(源码)

Introduction to software engineering - Chapter 2 - feasibility study

Search and recommend those things

SVN实测常用操作-记录操作大全

1279_VMWare Player安装VMWare Tools时VSock安装失败解决

C language_ Love and hate between string and pointer

直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
随机推荐
Redolog and binlog
Vulnhub靶机:BOREDHACKERBLOG: SOCIAL NETWORK
The first exposure of Alibaba cloud's native security panorama behind the only highest level in the whole domain
Selenium IDE的安装以及使用
Use of swift basic closure /block (source code)
FPGA的虚拟时钟如何使用?
Decltype usage introduction
Optimization and practice of Tencent cloud EMR for cloud native containerization based on yarn
有关iframe锚点,锚点出现上下偏移,锚点出现页面显示问题.iframe的srcdoc问题
Methods of vector operation and coordinate transformation
Keep one decimal place and two decimal places
Vulnhub target: boredhackerblog_ CLOUD AV
Latest news of awtk: new usage of grid control
Unity culling related technologies
The monthly salary of two years after graduation is 36K. It's not difficult to say
The applet reads more than 20 data, and the cloud function reads more than 100 restrictions
Chapter 1 overview of canvas
Vulnhub target: boredhackerblog: social network
搜索与推荐那些事儿
Vscode topic recommendation