7

leetcode 30. 串联所有单词的子串

 3 years ago
source link: https://iamxcb.com/leetcode-30.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

leetcode 30. 串联所有单词的子串

发表于 2019-07-16

| 0

| 阅读次数:

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:
输入:
s = “barfoothefoobarman”,
words = [“foo”,”bar”]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 “barfoor” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:
输入:
s = “wordgoodgoodgoodbestword”,
words = [“word”,”good”,”best”,”word”]
输出:[]

暴力解法,直接通过哈希表判断每个子串是否符合题目要求

示例代码(go)

func findSubstring(s string, words []string) []int {
res := make([]int, 0)
m, k := len(words), len(s)
if m == 0 || k == 0{
return res
}
n := len(words[0])
hashW := make(map[string]int)
for _, word := range words {
hashW[word]++
}
for i := 0; i <= k-m*n; i++ {
if isSubstring(s[i:i+m*n], m, n, hashW) {
res = append(res, i)
}
}
return res
}

func isSubstring(s string, m, n int, hashW map[string]int) bool {
hashS := make(map[string]int)
for i := 0; i < m*n; i += n {
hashS[s[i:i+n]]++
if hashW[s[i:i+n]] < 1 || hashS[s[i:i+n]] > hashW[s[i:i+n]] {
return false
}
}
return true
}
Code 1: The app is disabled for violation of user agreement.
Powered By Valine
v1.3.9

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK