查找子串,并且按字典顺序排序

没事刷刷题。

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
Example 1:
a1 = [“arp”, “live”, “strong”]
a2 = [“lively”, “alive”, “harp”, “sharp”, “armstrong”]
returns [“arp”, “live”, “strong”]
Example 2:
a1 = [“tarp”, “mice”, “bull”]
a2 = [“lively”, “alive”, “harp”, “sharp”, “armstrong”]
returns []
Notes:
Arrays are written in “general” notation. See “Your Test Cases” for examples in your language.
Beware: r must be without duplicates.

我的答案:

#include 
#include 
#include 
#include 
using namespace std;

class WhichAreIn
{

public:
    static std::vector<std::string> inArray(std::vector<std::string> &array1, std::vector<std::string> &array2)
    {
        std::vector<std::string> ret;
        for(int i=0;ifor(int j=0;jif(strstr(array2[j].c_str(),array1[i].c_str()))
                {
                    ret.push_back(array1[i].c_str());
                    for(int k=ret.size()-1;k>0;k--)
                    {
                        if(strcmp(ret[k].c_str(),ret[k-1].c_str())<0)
                        {
                            swap(ret[k],ret[k-1]);
                        }
                        else
                            break;
                    }
                    break;
                }
            }
        }
        return ret;
    }
};
int main()
{
    std::vector<std::string> arr1 ={"22""code""uydfd""live"};
    std::vector<std::string> arr2 ={"lively""alive""223""code""sharp"};
    std::vector<std::string> ans1 = WhichAreIn::inArray(arr1, arr2);
    system("pause");
    return 0;
}

你可能感兴趣的:(codewars)