Skip to content

[LeetCode] 30. 串联所有单词的子串 #68

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

Open
Animenzzzz opened this issue Sep 5, 2019 · 0 comments
Open

[LeetCode] 30. 串联所有单词的子串 #68

Animenzzzz opened this issue Sep 5, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个字符串 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"]
输出:[]

解题思路:首先先将words单词表用hash表存起来。然后遍历字符串,一步一步截取长度为 单词个数*单词长度 的子串,然后用这个子串去和哈希表比对,如果当前子串的子串(即单词)在哈希表中没有映射,则跳出,说明此子串不是要找的串。。。一直循环。

C++解题:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        if(!s.size() || !words.size()) return {};
        unordered_map<string,int> map;
        int wordsize = 0;
        for(string ss:words){
            map[ss]++;
            wordsize = int(ss.size());
        } 
        vector<int> res;
        int subStringSize = int(words.size())*wordsize;
        for (int i = 0; i <=  int(s.size()) - subStringSize; i++)
        {
            string subS = s.substr(i,subStringSize);
            unordered_map<string,int> map_tmp = map;
            bool flag = true;
            int j = 0;
            while (j<subStringSize)
            {
                string subSS = subS.substr(j,wordsize);
                if(map_tmp[subSS]){
                    map_tmp[subSS]--;
                }else{
                    flag = false;
                    break;
                }
                j = j+wordsize;
            }
            if (flag) res.push_back(i);
        }
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant