LeetCode习题:多次搜索

题目描述:给定一个较长字符串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]]

####提示:

  • 0 <= len(big) <= 1000
  • 0 <= len(smalls[i]) <= 1000
  • smalls的总字符数不会超过 100000。
  • 你可以认为smalls中没有重复字符串。
  • 所有出现的字符均为英文小写字母。
解题思路:利用 Trie树 这种数据结构,将smalls中的字符串构造成Trie树,然后遍历big中的子字符串匹配查询
解题语言: Swift
class Solution {
    func multiSearch(_ big: String, _ smalls: [String]) -> [[Int]] {
        let root = TrieNode()
        // 构造Trie树
        for i in 0..<smalls.count {
            if (smalls[i].count > 0) {
                insert(root, smalls[i], i)
            } 
        }
        var result = [[Int]](repeating: [], count: smalls.count)
        for i in 0..<big.count {
            let start = big.index(big.startIndex, offsetBy: i)
            let end = big.endIndex
            let subStr = String(big[start..<end])
            result = search(root, subStr, i, result)
        }
        return result
    }

    private func insert(_ node: TrieNode, _ word: String, _ flag: Int) {
        var currentNode = node
        for item in word {
            let index = Int(item.asciiValue!) - 97
            var subNode = currentNode.children[index]
            if subNode == nil {
                subNode = TrieNode()
                currentNode.children[index] = subNode
            }
            currentNode = subNode!
        }
        currentNode.flag = flag
        currentNode.isWord = true
    }

    private func search(_ node: TrieNode, _ word: String, _ flag: Int, _ list: [[Int]]) -> [[Int]] {
        var currentNode = node
        var newList = list
        for item in word {
            let index = Int(item.asciiValue!) - 97
            let subNode = currentNode.children[index]
            if subNode == nil {
                return newList
            } 
            if (subNode!.isWord) {
                newList[subNode!.flag].append(flag)
            }
            currentNode = subNode!
        }
        return newList
    }
}

class TrieNode {
    var isWord = false
    var children: [TrieNode?]!
    var flag: Int = -1
    
    init() {
        isWord = false
        children = [TrieNode?](repeating: nil, count: 26)
        flag = -1
    }
}
题目来源:LeetCode
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值