Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
yankewei opened this issue Mar 21, 2020 · 0 comments
Open

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

yankewei opened this issue Mar 21, 2020 · 0 comments
Labels
哈希表 题目包含哈希表解法 困难 题目难度为困难 字符串 题目类型为字符串

Comments

@yankewei
Copy link
Owner

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

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

示例 2:

输入:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
输出:[]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words

解答

获取如果完全匹配需要的总长度allLen := len(words) * len(words[0]), 然后遍历字符串,每次截断allLen的长度,然后按照单词的长度进行切分,进行比较即可

func findSubstring(s string, words []string) []int {
    var ret []int
    if len(words) == 0 {
        return ret
    }
    i, wordNum, wordLen, sLen := 0, len(words), len(words[0]), len(s)
    allLen := wordNum * wordLen
    if allLen > sLen {
        return ret
    }
    m := make(map[string]int)
    for _, v := range words {
        m[v]++
    }

    for (i+allLen) <= sLen {
        stop := false
        subStr := s[i : i+allLen]
        t := make(map[string]int)
        for l := 0; l < len(subStr); l += wordLen {
            if _, e := m[subStr[l:l+wordLen]]; !e {
                stop = true
                break
            }
            t[subStr[l:l+wordLen]]++
		}
        if stop {
            i++
            continue
        }
        for ii, v := range t {
            if vv, e := m[ii]; e && v == vv {
                delete(t, ii)
                continue
            }
            break
        }
        if len(t) == 0 {
            ret = append(ret, i)
        }
        i++
    }
    return ret
}
@yankewei yankewei added 困难 题目难度为困难 字符串 题目类型为字符串 哈希表 题目包含哈希表解法 labels Mar 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 困难 题目难度为困难 字符串 题目类型为字符串
Projects
None yet
Development

No branches or pull requests

1 participant