当前位置:网站首页>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("", +)
}
}
边栏推荐
猜你喜欢
Swift extension networkutil (network monitoring) (source code)
直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
Blue Bridge Cup_ Queen n problem
Examples of corpus data processing cases (reading multiple text files, reading multiple files specified under a folder, decoding errors, reading multiple subfolder text, batch renaming of multiple fil
Vulnhub靶机:BOREDHACKERBLOG: SOCIAL NETWORK
1279_ Vsock installation failure resolution when VMware player installs VMware Tools
Vulnhub target: boredhackerblog: social network
Leetcode 207: course schedule (topological sorting determines whether the loop is formed)
解决笔记本键盘禁用失败问题
More than observation | Alibaba cloud observable suite officially released
随机推荐
1279_ Vsock installation failure resolution when VMware player installs VMware Tools
os.path.join()使用过程中遇到的坑
From jsonpath and XPath to spl
对于flex:1的详细解释,flex:1
Keep one decimal place and two decimal places
decltype用法介绍
[teacher zhaoyuqiang] use the Oracle tracking file
Teach you how to use the reflect package to parse the structure of go - step 1: parameter type check
In the post epidemic era, the home service robot industry has just set sail
VsCode主题推荐
Solve the problem of notebook keyboard disabling failure
Vscode topic recommendation
Auto usage example
Case examples of corpus data processing (cases related to sentence retrieval)
transformers PreTrainedTokenizer类
51单片机_外部中断 与 定时/计数器中断
Future trends in automated testing
JDBC 在性能测试中的应用
直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)
2021-03-11 COMP9021第八节课笔记