LeedCode 30.串联所有单词的子串
ChatGPT给出的代码如下,提交结果正确:
想问一下为什么for循环中的边界条件是i<len呢,不是应该要i<wordLen才能遍历到字符串s中的每个字符吗?
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> answer;
int n = words.size();
int len = words[0].size();
int wordLen = n * len;
unordered_map<string, int> wordCount;
for( const string& word : words){
wordCount[word] ++;
}
for( int i = 0; i < len; i++){
int left = i;
int right = i;
unordered_map<string, int> currentCount;
while( right+len <= s.size()){
string a = s.substr( right, len);
right += len;
if( wordCount.find(a) != wordCount.end()){
currentCount[a] ++;
while( currentCount[a] > wordCount[a]){
string b = s.substr( left, len);
left += len;
currentCount[b] --;
}
if( right - left == wordLen){
answer.push_back(left);
}
}else{
left = right;
currentCount.clear();
}
}
}
return answer;
}
};
我改成i<wordLen后输出会变成下面这样:
我考虑过for循环是否是多余的,但当我删除后,结果也不正确: