题解 | #牛牛的串联子串游戏#

牛牛的串联子串游戏

https://www.nowcoder.com/practice/c1984371372b43f3b10bf6d0231520bb

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @param words string字符串vector 
     * @return int整型vector
     */
    vector<int> findSubstring(string s, vector<string>& words) {
        // write code here
        int k = words[0].size();
        int n = words.size();
        int i = 0;
        // map记录words
        map<string, int> dict;
        for (auto item : words) {
            if (dict.find(item) == dict.end()) {
                dict.emplace(item, 1);
            }
            else ++dict[item];
        }

        vector<int> res;
        int start = 0;
        i = n * k;
        // 用前n个字符串初始化
        for (int j = 0; j < i; j += k)
        {
            string substr = s.substr(j, k);
            if (dict.find(substr) != dict.end()) --dict[substr];
        }
        bool judge = true;
        for (auto it : dict)
        {
            judge &= (it.second == 0);
        }
        if (judge) res.push_back(start);

        while (i < s.size())
        {
            // 处理当前字符串
            string substr = s.substr(i, k);
            if (dict.find(substr) != dict.end()) --dict[substr];
            substr = s.substr(start, k);
            if (dict.find(substr) != dict.end()) ++dict[substr];
            i += k;
            start += k;

            bool judge = true;
            for (auto it : dict)
            {
                judge &= (it.second == 0);
            }
            if (judge) res.push_back(start);
        }
        return res;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 20:15
还能挽救吗?找同学帮忙看了一下&nbsp;字节怎么能如此对我
牛客26396789...:你这是严重红线,被发现你自己永远进不去,你那个同学直接走人,你还敢宣扬
点赞 评论 收藏
分享
北漂的牛马人:211佬,包进的,可能是系统问题
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务