当前位置:网站首页>13 -- remove invalid parentheses
13 -- remove invalid parentheses
2022-06-24 08:19:00 【JH_ Cao】
Remove invalid brackets
- Ideas
- encounter "(" Push
- encounter ")“, Check whether the stack is empty , The stack is empty. , Delete the current element
Stack is not empty. , Then take out the top element of the stack for comparison
If the elements at the top of the stack can form a pair ”()", Then remove the stack top element - After traversal , Look at the elements in the stack
- When storing stacks , Use a dictionary to store , This will record the index
- When deleting , Delete from back to front , Do not destroy the structure of the index
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 {
// The stack is not empty , Take out the top element of the stack to match , To match , Just delete
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("", +)
}
}
边栏推荐
猜你喜欢

Shader common functions

问题3 — messageBox弹框,修改默认背景色

Graphmae - - lecture rapide des documents

Part 1: building OpenGL environment

小样本故障诊断 - 注意力机制代码 - BiGRU代码解析实现

Ad-gcl:advantageous graph augmentation to improve graph contractual learning

More than observation | Alibaba cloud observable suite officially released

Coordinate transformation of graphic technology

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

jwt(json web token)
随机推荐
权限模型 DAC ACL RBAC ABAC
2022年流动式起重机司机特种作业证考试题库及在线模拟考试
Vulnhub target: boredhackerblog: social network
transformers PreTrainedTokenizer类
有关iframe锚点,锚点出现上下偏移,锚点出现页面显示问题.iframe的srcdoc问题
Question 1: the container that holds the most water
Upgrade Mysql to the latest version (mysql8.0.25)
小样本故障诊断 - 注意力机制代码 - BiGRU代码解析实现
Tool functions – get all files in the project folder
MySQL source and target table row count check
Methods of vector operation and coordinate transformation
Pagoda panel installation php7.2 installation phalcon3.3.2
VsCode主题推荐
Swift 基礎 閉包/Block的使用(源碼)
Robot acceleration level task priority inverse kinematics
基金的募集,交易与登记
Introduction to software engineering - Chapter 3 - Requirements Analysis
The applet reads more than 20 data, and the cloud function reads more than 100 restrictions
1-4metaploitable2 introduction
Simple summary of lighting usage