当前位置:网站首页>09 -- palindrome pair
09 -- palindrome pair
2022-06-23 12:14:00 【JH_ Cao】
Catalog
One 、 What is palindrome pair
1. The palindrome is right , It's a symmetric string , such as
"a"
"aba"
"aabb"
Two 、 subject
Give a group Different from each other 's words , Find out all Different The index of (i, j), Make two words in the list , words[i] + words[j] , Can be spliced into palindrome string .
Example 1:
Input :words = ["abcd","dcba","lls","s","sssll"]
Output :[[0,1],[1,0],[3,2],[2,4]]
explain : The palindrome string that can be spliced is ["dcbaabcd","abcddcba","slls","llssssll"]
3、 ... and 、 Their thinking
Palindrome + Flip
- hold words All strings in the array are flipped first , Then put it in a dictionary [String: Int]
- Yes words Array traversal
- If you traverse to an empty array , And the dictionary contains key The palindrome is right , Then add the answer
- Complexity :O(n^2)
for example :
1. words Flip , Add a dictionary , Then you will get the dictionary
[["dcba": 0], ["abcd": 1], ["sll": 2], ["s": 3], ["llsss": 4]]
2. An array words = ["abcd","dcba","lls","s","sssll"] Traversal
(1) For example, the current subscript is 2, Then the string is “lls”
From the subscript for 0 Start , Segmentation ,
left = "" , right = "lls", although left For palindromes to , but There is no... In the dictionary “lls” by key, Continue to split
left = "l", right = "ls", although left For palindromes to , But not in the dictionary “ls” by key, Continue to split
left = "ll", right = "s", left The palindrome is right , The dictionary also contains “s” by key, The subscript index = 2
["s": 3] Medium value = 3
Because the symmetrical section (left), It must be placed in the middle , The new string spliced together can also be a palindrome pair
So the string of the current subscript is placed after
that [3 , 2] The string composed of subscripts is “s” + "lls" == “slls”, It's palindrome yeah
(2) For example, the current subscript is 4, Then the string is “sssll”
From the subscript for 0 Start , Segmentation ,
left = "" , right = "sssll", although left For palindromes to , but There is no... In the dictionary “sssll” by key, Continue to split
left = "s", right = "ssll", although left For palindromes to , But not in the dictionary “ssll” by key, Continue to split
left = "ss", right = "sll", left The palindrome is right , The dictionary also contains “sll” by key, The subscript index = 4
["sll": 2] Medium value = 2
Empathy :
Because the symmetrical section (left), It must be placed in the middle , The new string spliced together can also be a palindrome pair
So the string of the current subscript is placed after
that [2, 4] => lls + sssll + = llssssll => It's palindrome yeah
(3) Empathy :
If the symmetrical section is (right) part , Then the string of the current subscript should be placed in front of
Put it all together [ index, dict[right]]
Code :
// Dictionary method
func palindromePairs(_ words: [String]) -> [[Int]] {
var dict = [String: Int]()
var res = [[Int]]()
words.enumerated().forEach { (index, str) in
dict[String(str.reversed())] = index
}
for (index, s) in words.enumerated() {
if s.isEmpty {
dict.forEach { (Str, idx) in
if checkIsOK(Str) && index != idx {
res.append([index,idx])
}
}
}
for j in 0..<s.count {
let mid = s.index(s.startIndex, offsetBy: j)
let leftPart = String(s[..<mid])
let rightPart = String(s[mid...])
if checkIsOK(leftPart) && dict[rightPart] != nil && dict[rightPart] != index {
res.append([dict[rightPart]!, index])
}
if checkIsOK(rightPart) && dict[leftPart] != nil && dict[leftPart] != index {
res.append([index, dict[leftPart]!])
}
}
}
return res
}
func checkIsOK(_ s: String) -> Bool {
return s == String(s.reversed())
}Two layers of for loop
Add strings one by one , Then try to adjust left and right , Concatenate new strings , Determine whether the new string is a palindrome pair , This kind of thinking is relatively easy to understand
Complexity : O(n^2)
Code :
// Splicing method
func palindromePairsTimeout(_ words: [String]) -> [[Int]] {
let n = words.count
var res = [[Int]]()
for i in 0..<n-1 {
let str1 = words[i]
for j in i+1..<n {
let str2 = words[j]
if checkIsOK(str1 + str2) {
res.append([i,j])
}
if checkIsOK(str2 + str1) {
res.append([j,i])
}
}
}
return res
}
func checkIsOK(_ s: String) -> Bool {
return s == String(s.reversed())
}边栏推荐
- ROS knowledge: point cloud files PCD format
- 机器学习系列5:距离空间(1)
- 2022年全国最新消防设施操作员(初级消防设施操作员)模拟题及答案
- 2D laser Slam (using laser scan matcher)
- Surprise! Amd acquires Xilinx with USD 35billion!
- ROS知识:rviz库librviz的结构
- 全国进入主汛期,交通运输部:不具备安全运行条件的线路坚决停运!
- 我在佛山,到哪里开户比较好?手机开户安全么?
- Blue Bridge Cup single chip microcomputer (I) -- turn off peripherals and turn off led
- halcon原理:一维函数function_1d类型【2】
猜你喜欢

Qt5 knowledge: some key points of signals and slots

Blue Bridge Cup single chip microcomputer (I) -- turn off peripherals and turn off led

公开课丨玩的就是短视频!今晚教你精准变现!

HMS Core 视频编辑服务开放模板能力,助力用户一键Get同款酷炫视频

Easy to understand soft route brushing tutorial

@Dark horse fans, haven't you received this "high temperature subsidy"?

【零基础微信小程序】基于百度大脑人像分割的证件照换底色小程序实战开发

二維激光SLAM( 使用Laser Scan Matcher )

Machine Learning Series 5: distance space (1)

PPT制作3D旋转动画从入门到进阶
随机推荐
利用XtraDiagram.DiagramControl进行流程图形的绘制和控制
学习笔记 scrapy 爬虫框架
Proof and application of Chebyshev inequality
电脑坏了,换了台电脑,装node环境的时候出了问题,报错URL not defined
Redis 入门-第三篇-数据结构与对象-字典
[cloud native & microservice viii] source code analysis of weightedresponsetimerule of ribbon load balancing strategy (response time weighting)
With 32 qubits! Rigetti computing enters the UK quantum computing market
详解PyQt5信号与槽的关系
Easy to understand soft route brushing tutorial
HMS Core 视频编辑服务开放模板能力,助力用户一键Get同款酷炫视频
Surprise! Amd acquires Xilinx with USD 35billion!
Use monotone stack to solve problems
[zero foundation wechat applet] actual development of ID photo changing background color applet based on Baidu brain portrait segmentation
Open classes are short videos! Tonight, I will teach you how to realize accurately!
Does the inductance have polarity?
2022工具钳工(初级)考试练习题模拟考试平台操作
生态 | 万里数据库与卫士通完成兼容认证 共筑网络安全生态体系
[comprehensive written test questions] 30 Concatenate substrings of all words
Internet miracle - how does Xiaomi make profits
想学习eTS开发?教你开发一款IQ-EQ测试应用