[Swift]LeetCode1100. 长度为 K 的无重复字符子串 | Find K-Length Substrings With No Repeated Characters
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11075293.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a string S
, return the number of substrings of length K
with no repeated characters.
Example 1:
Input: S = "havefunonleetcode", K = 5
Output: 6
Explanation:
There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'.
Example 2:
Input: S = "home", K = 5
Output: 0
Explanation:
Notice K can be larger than the length of S. In this case is not possible to find any substring.
Note:
1 <= S.length <= 10^4
- All characters of S are lowercase English letters.
1 <= K <= 10^4
给你一个字符串 S
,找出所有长度为 K
且不含重复字符的子串,请你返回全部满足要求的子串的 数目。
示例 1:
输入:S = "havefunonleetcode", K = 5 输出:6 解释: 这里有 6 个满足题意的子串,分别是:'havef','avefu','vefun','efuno','etcod','tcode'。
示例 2:
输入:S = "home", K = 5 输出:0 解释: 注意:K 可能会大于 S 的长度。在这种情况下,就无法找到任何长度为 K 的子串。
提示:
1 <= S.length <= 10^4
S
中的所有字符均为小写英文字母1 <= K <= 10^4
44ms
1 class Solution { 2 func numKLenSubstrNoRepeats(_ S: String, _ K: Int) -> Int { 3 var ans:Int = 0 4 let n:Int = S.count 5 let S:[Int] = Array(S).map{$0.ascii} 6 for i in 0..<n 7 { 8 var freq:[Int] = [Int](repeating:0,count:26) 9 var j:Int = i 10 var len:Int = 0 11 while(j < n) 12 { 13 //a:97 14 if freq[S[j] - 97] != 0 {break} 15 freq[S[j] - 97] += 1 16 len += 1 17 j += 1 18 if len == K 19 { 20 ans += 1 21 } 22 } 23 } 24 return ans 25 } 26 } 27 28 //Character扩展 29 extension Character 30 { 31 //Character转ASCII整数值(定义小写为整数值) 32 var ascii: Int { 33 get { 34 return Int(self.unicodeScalars.first?.value ?? 0) 35 } 36 } 37 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了