欢迎光临散文网 会员登陆 & 注册

leetcode c++ 串联所有单词的子串

2023-02-09 22:39 作者:神兮兮的喵社长  | 我要投稿

我的解:

时间击败了7.71%,内存击败了18.3%(挺垃圾的)

#include <vector>

using namespace std;

class Solution {

public:

    vector<int> findSubstring(string s, vector<string>& words) {

        int len_w = words.back().length();

        int len_all = len_w * words.size();

        int len_s = s.length();


        vector<string> word;

        word.assign(words.begin(), words.end());

        std::sort(word.begin(), word.end());

        std::unique(word.begin(), word.end());


        vector<int> counts;

        for (int i =0;i<word.size();i++)

        {

            counts.push_back(std::count(words.begin(), words.end(), word.at(i)));

        }


        bool flag;

        vector<int> indexes;

        vector<string> temp;

        string str;

        for (int i=0; i<len_s && (len_s-i)>=len_all;i++)

        {  

            flag = true;

            temp.clear();

            for(int j =0;j < words.size();j++)

            {

                temp.push_back(s.substr(i+j*len_w,len_w));

            }


            for (int k =0;k<word.size();k++)

            {

                if(std::count(temp.begin(),temp.end(), word.at(k)) !=counts.at(k))

                {

                    flag=false;

                    break;

                }

            }


            if (flag)

            {

                indexes.push_back(i);

            }

        }


        return indexes;

    };

};



leetcode c++ 串联所有单词的子串的评论 (共 条)

分享到微博请遵守国家法律