当前位置:网站首页>LeetCode/Scala - without the firstborn of the string of characters, the longest text string back
LeetCode/Scala - without the firstborn of the string of characters, the longest text string back
2022-07-30 00:55:00 【BIT_666】
一.引言
LeetCode There is a class of string substring problems,这里主要分析无重复字符的最长子串与最长回文子串,Summarize related methods.
二.无重复字符最长子串
1.题目要求
给定字符串 s,Ask to find the longest substring without repetitions within a character,Note that a substring is not a subsequence.
2.Sliding pointer method
A.思路分析
通过 start 与 end Double pointer to specify the longest substring range,通过 HashMap 记录每一个 char The index of the character and implement deduplication.
-> Iterate over all strings char 字符
-> Determine whether the current character is present HashMap 中,并更新当前 start
-> end += 1,并记录当前 char 对应的索引
-> length = end - start,比较 length 与 maxLength 并更新最大长度
B.代码实现
def solution(s: String): Int = {
// Double pointer and indexMap
var maxLength = 0
var start = 0
var end = 0
val indexMap = mutable.HashMap[Char, Int]()
// 转换为char
val arr = s.toCharArray
s.toCharArray.foreach(char => {
if (indexMap.contains(char)) {
start = math.max(indexMap(char), start) // 更新 start
}
end += 1 // 更新 end
indexMap(char) = end
maxLength = math.max(end - start, maxLength) // 更新 maxLength
println(s"char: $char start: $start end: $end max: $maxLength arr: ${s.slice(start, end).mkString("")}")
})
maxLength
}
为了直观,We have added log printing,以 s = "abba" 为例进行测试:
def main(args: Array[String]): Unit = {
val s = "abba"
println(solution(s))
}
Double pointers can be understood in conjunction with the execution process start 和 end 的变化.
C.执行效率
时间复杂度 O(n),其中 n 为字符串的长度,即 char 的数量,空间复杂度为 O(|∑|),其中 ∑ A deduplication set for the current string,The normal case can be approximated as O(n),极端情况例如 s="11111" 则退化为 O(1).
三.最长回文子串
1.题目要求
给定字符串 s,Find its longest palindrome substring,Here is an explanation of what a palindrome is,That is, positive and negative strings,例如 aabbaa,aba,ccccc Both are palindromic substrings,Note that the longest non-repeating substring returns the length of the string whereas this example returns the string.
2.中心扩展法
A.思路分析
First clarify the transition conditions for palindromic characters,假设 P(i,j) 为回文子串,如果 i-1,j+1 The corresponding position elements are the same,则 P(i-1, j+1) 也是回文子串,如此类推.
-> 初始化 maxLeft,maxRight Record the interval of the longest palindrome,初始化 maxLength 记录最长长度
-> Traverse the array array index,Explore to the left,当前索引为 mid,Then the left side is mid - 1,如果 s(mid) = s(left) 则 P(left, mid) 构成回文子串,left -=1 Continue to explore left
-> Explore to the right,方法同上,right = mid + 1,判断 s(mid) 与 s(right)
-> 向Expanded on both sides,One-way expansion mainly looks for AND mid Elements with the same elements,例如 a -> aaa,Bilateral is mainly to find the same elements on both sides,例如 aaa -> baaab,判断 s(left) = s(right)
-> 更新 maxLeft,maxRight Record the current longest palindrome range
B.代码实现
// 中心扩展算法
def solution(s: String): String = {
var length = 1
// 从每个 mid 开始向两边扩散
var maxLeft = 0 // 起点
var maxRight = 0 // 终点
var maxLength = 0 // 最长回文串长度
val arr = s.toCharArray
arr.indices.foreach(mid => {
var left = mid - 1
var right = mid + 1
// Expand to the left
while (left >= 0 && arr(left).equals(arr(mid))) {
left -= 1
length += 1
}
// Expand to the right
while (right <= arr.length - 1 && arr(right) == arr(mid)) {
right += 1
length += 1
}
// 向Expanded on both sides
while (left >= 0 && right <= arr.length - 1 && arr(left) == arr(right)) {
left -= 1
right += 1
length += 2
}
// 更新
if (length > maxLength) {
maxLeft = left
maxRight = right
maxLength = length
}
length = 1
})
println(maxLeft, maxRight, maxLength)
s.substring(maxLeft + 1, maxRight)
}
分别向左,右,Expanded on both sides,The last update interval,You can refer to the above analysis,After the judgment is equal,继续 left -= 1 寻找下一个 left,So the final satisfied left boundary is realLeft = maxLeft + 1,maxRight 同理,maxRight = realRight + 1,所以最终结果 subString(maxLeft + 1,maxRight).
C.执行效率
Ou a handful,Not sure how this commit ran so fast,算法时间复杂度 O(n^2),因为遍历 n 个字符,Each character expands left and right,空间复杂度 O(1).
四.总结
It can be seen that many algorithms are used 双指针、HashMap,It is therefore important to understand their common usage and boundary conditions,The second palindrome is due to P(i,j) 向 P(i-1,j+1) transfer status,Also applies to dynamic programming,There will be time to sort out dynamic programming later.
边栏推荐
- 谷歌浏览器(google)设置翻译中文,翻译选项不生效或没有弹出翻译选项
- 转发和重定向的区别及使用场景
- Running a Fabric Application
- Weekly recommended short video: What is R&D efficiency?It can achieve anti "involution"?
- 二叉排序树(C语言)
- LeetCode / Scala - 无重复字符最长子串 ,最长回文子串
- 【微服务~Nacos】Nacos之配置中心
- Toutiao We-Media Operation: How to Gain 500+ Fans in Toutiao Today?
- canvas 中如何实现物体的框选(六)
- Docker installs redis cluster (including deployment script)
猜你喜欢
Low dropout linear regulator MPQ2013A-AEC1 brand MPS domestic replacement
[Training DAY16] ALFA [convex hull] [computational geometry]
Fabric 编写案例 链码
自学HarmonyOS应用开发(47)- 自定义switch组件
利用热点事件来创作软文的3大技巧?自媒体人必看
He cell separation technology 丨 basic primary cell separation methods and materials
Unity笔记——FairyGUI
Worthington木瓜蛋白酶&胰凝乳蛋白酶&脱氧核糖核酸酶 I
Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE
BEVDetNet: Bird's Eye View LiDAR Point Cloud based Real-time 3D Object Detection for Autonomous Drivi
随机推荐
【经验】经验总结-经验教训
自学HarmonyOS应用开发(53)- 获取当前位置
How Filebeat ensures that the log file is still correctly read when the log file is split (or rolled)
BEVDetNet: Bird's Eye View LiDAR Point Cloud based Real-time 3D Object Detection for Autonomous Drivi
自媒体短视频标题怎么写?3个爆款标题,让你的视频收获更多流量
自学HarmonyOS应用开发(49)- 引入地图功能
自媒体短视频怎么提高播放量?从这三个方面入手
i.MX6U-driver development-3-new character driver
Fabric 编写案例 链码
高德地图jsapi不生效 INVALID_USER_SCODE
2022-07-29:一共有n个人,从左到右排列,依次编号0~n-1, h[i]是第i个人的身高, v[i]是第i个人的分数, 要求从左到右选出一个子序列,在这个子序列中的人,从左到右身高是不下降的。
从尾到头打印链表
Unity笔记——FairyGUI
Linux-安装MySQL(详细教程)
Low dropout linear regulator MPQ2013A-AEC1 brand MPS domestic replacement
Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE
Fabric 私有数据案例
利用热点事件来创作软文的3大技巧?自媒体人必看
微信开发者工具设置制表符大小为2
谷歌浏览器(google)设置翻译中文,翻译选项不生效或没有弹出翻译选项