当前位置:   article > 正文

LeetCode第30题:Substring with Concatenation of All Words(C++图文详解)_leetcode 30

leetcode 30
  1. 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 “barfoor” 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: []

题目详解:
1.此题得难度在于words中单词可重复;
2.单纯遍历给定字符串,无法判断;
3.思路是将words中每个单词存入map中,因可重复,故存入unordered_map;
4.因words中单词定长,可算出长度,故遍历给定字符串,只需到(字符串长度减去words中单词总长度);

代码:

#include "pch.h"
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> findSubstring(string s, vector<string>& words) {
	if (s.empty() || words.empty()) return {};
	vector<int> resVec;//返回数组
	int n = words.size(), len = words[0].size();
	unordered_map<string, int> wordsMap;
	for (auto &word : words) ++wordsMap[word];
	for (int i = 0; i <= (int)s.size() - n * len; i++) {
		unordered_map<string, int> sMap;
		int j = 0;
		for (j = 0; j < n; j++) {
			string t = s.substr(i + j * len, len);//截取定长子字符串(words中单词定长)
			if (!wordsMap.count(t)) break;//当前截取子字符串不在map中,终止
			++sMap[t];
			if (sMap[t] > wordsMap[t]) break;//子字符串值不相等,终止
		}
		if (j == n) resVec.push_back(i);//连续给定子字符串都相等,则为所要值
	}
	return resVec;
}
int main()
{
	/*string s = "wordgoodgoodgoodbestword";
	vector<string> words = { "word", "good", "best", "word" };*/
	string s = "barfoothefoobarman";
	vector<string> words = {"foo", "bar"};
	vector<int> res = findSubstring(s, words);
	for (int i = 0; i < res.size(); i++)
	{
		cout << res[i];
		cout << "\n";
	}
	
    std::cout << "Hello World!\n"; 
	system("PAUSE");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

图文详解:
在这里插入图片描述

性能:
在这里插入图片描述

总结:此题目主要考察对Map得使用,采用其他方法可能比较费劲;容器得原理和理解,在数据结构中尤为重要;继续加油!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/252576
推荐阅读
相关标签
  

闽ICP备14008679号