LeetCode 29. Substring with Concatenation of All Words

暴力匹配。

用一张map统计L的单词及频数;

另一张map再迭代中记录自当前迭代下标begin起的子串的单词频数,当当前频数超过总频数时重新迭代:

if (++ tmp[S.substr(begin+i*word_size, word_size)] > cnt[S.substr(begin+i*word_size, word_size)] )
{
<span style="white-space:pre">	</span>break;
}

完整代码:

class Solution 
{
public:
	vector<int> findSubstring(string S, vector<string> &L) 
	{
		if( L.empty() == true )
		{
			return vector<int>();
		}
		vector<int> ret;
		map<string, int> cnt;
		int word_size = L[0].size();
		for (auto it = L.begin(); it != L.end(); ++ it)
		{
			++ cnt[*it];
		}    

		for (int begin = 0; begin <= int(S.size())-int(L.size()*word_size); ++ begin)
		{
			map<string, int> tmp;
			size_t i = 0;
			for ( ; i < L.size(); ++ i)
			{
				if (++ tmp[S.substr(begin+i*word_size, word_size)] > cnt[S.substr(begin+i*word_size, word_size)] )
				{
					break;
				}
			}
			if (i == L.size())
			{
				ret.push_back(begin);
			}
		}

		return ret;
	}
};


你可能感兴趣的:(LeetCode,C++,String)