Substring with Concatenation of All Words__leetcode_go

題目描述

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

思路:

  • 題的特點是被匹配字串都是等長的。所以才能將子串的單詞子串,易于用哈希O(1)查找。
  • 匹配集合用哈希表計數(shù)。遍歷子串及子串的單詞子串,存在則加入已匹配哈希。
  • 這些情況放棄當前子串匹配:單詞子串匹配次數(shù)超出,單詞子串不匹配。

細節(jié):

  • 輸入條件檢查: if s == "" || len(words) == 0{return nil}
  • 哈希表put需要判斷,所以多寫了幾行代碼。

解:

package main

import "fmt"

func findSubstring(s string, words []string) []int {
    if s == "" || len(words) == 0{return nil}
    res := make([]int,0,len(s))
    sSlice := []rune(s)
    wordsMap := make(map[string]int, len(words))
    lenWord := len(words[0])
    lenSubstr := lenWord * len(words)
    for _, elem := range words {
        _, ok := wordsMap[elem]
        if ok {
            wordsMap[elem] = wordsMap[elem] + 1
        } else {
            wordsMap[elem] = 1
        }
    }
    for i := 0; i <= len(s)-lenSubstr; i++ {
        subMap := make(map[string]int,len(words))
        j :=0
        for ;j<len(words);j++ {
            subStr := string(sSlice[i+j*lenWord:i+j*lenWord+lenWord])
            if num,ok := wordsMap[subStr];ok {
                if numSub,ok := subMap[subStr];ok{
                    subMap[subStr] = numSub+1
                    if numSub+1 > num {
                        break
                    }
                }else {
                    subMap[subStr] = 1
                }
            } else {
                break
            }
        }
        if j == len(words) {
            res = append(res,i)
        }
    }
    if len(res) == 0 {return nil}
    return res
}

func main()  {
    s := "aaaaaaaa"
    words := []string{"aa","aa","aa"}
    res := findSubstring(s,words)
    fmt.Print(res)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容