本文主要是介绍leetcode_32 Substring with Concatenation of All Words,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:串联所有单词的子串
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 "barfoo" and "foobar" respectively. The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] Output: []
题目大意:给出单词列表,所有单词的长度相同,这些所有单词可能组成的字符串,在字符串s中出现的可能位置
原理解析:
I think the following code is self-explanatory enough. We use an unordered_map<string, int> counts
to record the expected times of each word and another unordered_map<string, int> seen
to record the times we have seen. Then we check for every possible position of i
. Once we meet an unexpected word or the times of some word is larger than its expected times, we stop the check. If we finish the check successfully, push i
to the result indexes
. 我们用一个hashmap来记录words中的单词,及单词出现的次数(每个单词长度wlen,一共有n个单词,则子串的长度为wlen*n)。然后用另一个hashmap来记录相同长度(wlen*n长度)的子串中,子串是从字符串s的0位置开始,长度为 wlen*n的字符串, 每个单词(每个wlen长度为一个单词)及单词出现的次数,同时判断单词是否在前一个hashmap中出现,如果没有,则进入下一个循环。如果出现过,则记录在hashmap中,记录完之后,判断记录进的个数比前一个hashmap记录单词的个数大,如果大,就进入下一个循环。否则继续判断下一个单词,如果因大于单词个数n循环退出,说明,n个单词都在hashmap中出现过,且个数不超过,则个数相等,则该子串是要找的子串,记录此时的循环变量i,然后i++,在进行下一个子串的判断,直至 (int) s.size() - wlen*n 为最后一个子串的首位。
注意:s.size()是无符号整数,减去一个比自己大的数字,会出错。
class Solution {
public:vector<int> findSubstring(string s, vector<string>& words) {vector<int> res;if(s.empty() || words.empty())return res;unordered_map<string,int> word_cnt;for(int i = 0; i < words.size(); i++){word_cnt[words[i]]++;}int wlen = words[0].length();int n = words.size();int sublen = wlen * n;for(int i = 0; i <= (int)s.size() - sublen;i++){unordered_map<string,int> str_cnt;int j = 0;for(j = 0;j < n; j++){string str = s.substr(i + j*wlen,wlen);if(!word_cnt.count(str)) break;str_cnt[str]++;if(str_cnt[str] > word_cnt[str]) break;}if(j == n)res.push_back(i); }return res;}
};
这篇关于leetcode_32 Substring with Concatenation of All Words的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!