★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-orhalfbw-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given string S
and a dictionary of words words
, find the number of words[i]
that is a subsequence of S
.git
Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There are three words in that are a subsequence of : "a", "acd", "ace". wordsS
Note:github
words
and S
will only consists of lowercase letters.S
will be in the range of [1, 50000]
.words
will be in the range of [1, 5000]
.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"。
注意:app
words
和 S
裏的單詞都只由小寫字母組成。S
的長度在 [1, 50000]
。words
的長度在 [1, 5000]
。words[i]
的長度在[1, 50]
。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 }
1168msspa
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 }