当前位置:网站首页>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("", +)
}
}
边栏推荐
- From jsonpath and XPath to spl
- Swift extension chainlayout (UI chain layout) (source code)
- Graphmae ---- quick reading of papers
- 1279_ Vsock installation failure resolution when VMware player installs VMware Tools
- OC Extension 检测手机是否安装某个App(源码)
- How to use the virtual clock of FPGA?
- Vulnhub target: boredhackerblog: social network
- [测试开发]初识软件测试
- 解决笔记本键盘禁用失败问题
- Leetcode 174 Dungeon games (June 23, 2022)
猜你喜欢

Echart's experience (I): about y axis yaxis attribute

2022茶艺师(中级)上岗证题库及在线模拟考试
![[run the script framework in Django and store the data in the database]](/img/6b/052679e5468e5a90be5c4339183f43.png)
[run the script framework in Django and store the data in the database]

Swift 基礎 閉包/Block的使用(源碼)

Swift 基础 Swift才有的特性

自动化测试的未来趋势

Simple summary of lighting usage

Synchronous FIFO

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

C language_ Love and hate between string and pointer
随机推荐
Qopengl display point cloud file
自动化测试的未来趋势
Saccadenet: use corner features to fine tune the two stage prediction frame | CVPR 2020
1279_VMWare Player安装VMWare Tools时VSock安装失败解决
Installation and use of selenium IDE
2022 PMP project management examination agile knowledge points (1)
3-list introduction
1279_ Vsock installation failure resolution when VMware player installs VMware Tools
Dart development server, do I have a fever?
Swift Extension ChainLayout(UI的链式布局)(源码)
4-operation list (loop structure)
Swift extension chainlayout (UI chain layout) (source code)
Shader common functions
Simple refraction effect
2022年流动式起重机司机特种作业证考试题库及在线模拟考试
2022年制冷与空调设备运行操作上岗证题库及模拟考试
Swift extension networkutil (network monitoring) (source code)
LabVIEW查找n个元素数组中的质数
How to use the virtual clock of FPGA?
Future trends in automated testing