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

  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");
}

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

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

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值