LeetCode-30. 串联所有单词的子串(Substring with Concatenation of All Words)

哈希(待优化)

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
    	vector<int> res;
    	if(s.size() == 0 || words.size() == 0)	return res;
    	unordered_map<string, int> map;
    	int one_word_len = words[0].size();
    	int words_num = words.size();
    	int words_len = one_word_len * words_num;
    	for (int i = 0; i < words.size(); ++i)
    	{
    		map[words[i]]++;
    	}
    	for (int i = 0; i < s.size() - words_len + 1; ++i)
    	{
    		int flag = 1;
    		string temp = s.substr(i, words_len);
    		unordered_map<string, int> temp_map;
    		for (int j = 0; j < words_len; j += one_word_len)
    		{
    			string t = temp.substr(j, one_word_len);
    			temp_map[t]++;
    		}
    		for (int j = 0; j < words_num; ++j)
    		{
    			if(temp_map[words[j]] != map[words[j]]){
    				flag = 0;
    				break;
    			}
    		}
    		if(flag) res.push_back(i);
    	}
    	return res;
    }
};

题目链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/

发布了42 篇原创文章 · 获赞 2 · 访问量 1403

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/103162951