1. 程式人生 > 其它 >LeetCode 792. 匹配子序列的單詞數(二分查詢)

LeetCode 792. 匹配子序列的單詞數(二分查詢)

技術標籤:LeetCode

文章目錄

1. 題目

給定字串 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]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-matching-subsequences
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

2. 解題

  • 把 S 的每個字元的下標,分類順序存在一起
  • 二分查詢每個單詞裡的字母在大於前一個字元的位置,且最小的下標位置
class Solution {
public:
    int numMatchingSubseq(string S, vector<string>
& words) { vector<vector<int>> pos(26); for(int i = 0; i < S.size(); i++) { pos[S[i]-'a'].push_back(i); } int ans = 0; for(auto& w : words) { int maxpos = -1, j = 0; for( ; j < w.size()
; j++) { int idx = w[j]-'a'; auto it = lower_bound(pos[idx].begin(), pos[idx].end(), maxpos+1); if(it == pos[idx].end()) break; maxpos = *it; } if(j == w.size()) ans++; } return ans; } };

364 ms 39.7 MB C++


我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明