leetcode —— 面試題 17.多次搜索

給定一個較長字符串big和一個包含較短字符串的數組smalls,設計一個方法,根據smalls中的每一個較短字符串,對big進行搜索。輸出smalls中的字符串在big裏出現的所有位置positions,其中positions[i]爲smalls[i]出現的所有位置。

示例:

輸入:
big = “mississippi”
smalls = [“is”,“ppi”,“hi”,“sis”,“i”,“ssippi”]
輸出: [[1,4],[8],[],[3],[1,4,7,10],[5]]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/multi-search-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
——————————
解題思路:將big的所有出現的字母的索引位置放在字典中,對於smalls中的每個單詞,通過其首字母找到big中對應字母的起始位置,比較兩個字符串是否相等,相等則進行記錄。

其Python代碼如下:

class Solution:
    def __init__(self):
        self.ans = []
    def multiSearch(self, big: str, smalls: List[str]) -> List[List[int]]:
        if not big:
            return [[] for _ in range(len(smalls))]
        dicts = dict()
        length = len(big)
        for i in range(length):  # 記錄big中每個字母可能出現的索引
            dicts.setdefault(big[i],[])
            dicts[big[i]].append(i)
        
        for s in smalls: 
            lens = len(s)
            if lens == 0 or s[0] not in dicts.keys():  # 如果small中字符串的長度爲零,或者字符串的首字母不在big中出現,直接返回空列表
                self.ans.append([])
                continue
            lists = []
            for index in dicts[s[0]]:  # 如果small的單詞的首字母出現在big中,找到big中對應字母的所有出現位置
                if index+lens-1<length and big[index:index+lens]==s:  # 比較兩個字符串是否相等
                    lists.append(index)
            self.ans.append(lists[:])  # 將記錄存放在ans列表中
        return self.ans
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章