姜肆爷 2023-09-26 15:39 采纳率: 76%
浏览 6

LeedCode串联所有单词的子串 代码细节疑问

LeedCode 30.串联所有单词的子串
ChatGPT给出的代码如下,提交结果正确:

img

想问一下为什么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后输出会变成下面这样:

img

我考虑过for循环是否是多余的,但当我删除后,结果也不正确:

img

  • 写回答

1条回答 默认 最新

  • 真相重于对错 2023-09-27 19:20
    关注

    因为要避免重复找到,符合要求的子串起始位置余len只有len种0到len-1,且不相交。

    评论

报告相同问题?

问题事件

  • 创建了问题 9月26日

悬赏问题

  • ¥15 基于python的adams二次开发
  • ¥15 wireMock设定默认文件问题
  • ¥20 NX二次开发TKLTOOS加载不出来
  • ¥15 诚意满满、携手共进、请多关照
  • ¥15 ubuntu下git下来的langchainchatchat没有config目录怎么办(语言-python)
  • ¥15 时间序列异常检测(python)
  • ¥15 anaconda navigator无法选择python版本
  • ¥15 DS1302时钟显示不稳定是怎么回事
  • ¥15 做一个简单的bp500元贵吗?
  • ¥15 为什么点击加入购物车跳转页面应用程序找不到对应的资源该怎么修改