在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given string Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There are three words in Note:
给定字符串 示例: 输入: S = "abcde" words = ["a", "bb", "acd", "ace"] 输出: 3 解释: 有三个是 S 的子序列的单词: "a", "acd", "ace"。 注意:
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 }
|
请发表评论