[Swift]LeetCode792. 匹配子序列的单词数 | Number of Matching Subsequences
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10547036.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given string S
and a dictionary of words words
, find the number of words[i]
that is a subsequence of S
.
words
S
Note:
- All words in
words
andS
will only consists of lowercase letters. - The length of
S
will be in the range of[1, 50000]
. - The length of
words
will be in the range of[1, 5000]
. - The length of
words[i]
will be in the range of[1, 50]
.
给定字符串 S
和单词字典 words
, 求 words[i]
中是 S
的子序列的单词个数。
示例: 输入: S = "abcde" words = ["a", "bb", "acd", "ace"] 输出: 3 解释: 有三个是 S 的子序列的单词: "a", "acd", "ace"。
注意:
- 所有在
words
和S
里的单词都只由小写字母组成。 S
的长度在[1, 50000]
。words
的长度在[1, 5000]
。words[i]
的长度在[1, 50]
。
Runtime: 740 ms
Memory Usage: 20 MB
1 class Solution { 2 func numMatchingSubseq(_ S: String, _ words: [String]) -> Int { 3 let arrS:[Character] = Array(S) 4 var res:Int = 0 5 var n:Int = S.count 6 var pass:Set<String> = Set<String>() 7 var out:Set<String> = Set<String>() 8 for word in words 9 { 10 let arrW:[Character] = Array(word) 11 if pass.contains(word) || out.contains(word) 12 { 13 if pass.contains(word) {res += 1} 14 continue 15 } 16 var i:Int = 0 17 var j:Int = 0 18 var m:Int = word.count 19 while (i < n && j < m) 20 { 21 if arrW[j] == arrS[i] {j += 1} 22 i += 1 23 } 24 if j == m 25 { 26 res += 1 27 pass.insert(word) 28 } 29 else 30 { 31 out.insert(word) 32 } 33 } 34 return res 35 } 36 }
1168ms
1 class Solution { 2 func numMatchingSubseq(_ S: String, _ words: [String]) -> Int { 3 var indices = [Character: [Int]]() 4 let S = Array(S.characters) 5 for i in 0..<S.count { 6 indices[S[i], default:[]].append(i) 7 } 8 9 func binarySearch(_ ch: Character, _ from: Int) -> Int { 10 guard let arr = indices[ch] else { return -2 } 11 if from > arr.last! { return -2 } 12 13 var l = 0, r = arr.count - 1 14 while l < r { 15 let mid = (l + r) / 2 16 if arr[mid] < from { 17 l = mid + 1 18 } else { 19 r = mid 20 } 21 } 22 return arr[r] 23 } 24 25 var res = 0 26 for w in words { 27 var from = 0 28 for ch in w.characters { 29 from = binarySearch(ch, from) + 1 30 if from < 0 { break } 31 } 32 if from >= 0 { res += 1 } 33 } 34 return res 35 } 36 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了