这是亚麻2018 年的新题2
// find all the N substring with only one duplicate character. #include <iostream> // std::cout #include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap #include <vector> // std::vector #include <unordered_map> #include <numeric> //use a slide window to mared each matched range and record the optimal result. //use the hash map to index the each substring in target. //iterate all substring in available container and find out each slide window that is marked with the updated indexs stored in a vector container. using namespace std; std::vector<int> subStringKDistance(std::vector<std::string>& available, std::vector<std::string>& target){ if (available.size() < target.size() || available.size ()== 0 || target.size() ==0 ) return std::vector<int>(); std::unordered_map<std::string, int> hashmap; // map substring in target to index. int i = 0; for (auto e: target){ hashmap[e] = i++; } if (hashmap.size() != target.size()) return std::vector<int>(); for (auto& e: hashmap) std::cout << e.first << " " << e.second; //create container to store the indexs of each substring in available list. std::vector<int > indexs(hashmap.size(), INT_MAX); int ind1 = 0; int ind2 =0; int distance = INT_MAX; int index = 0; for (auto e: available){ if ( hashmap.find(e) == hashmap.end()) {// the string is not in target list. index++; std::cout<< e << " not found"<<std::endl; continue ; //use find to check if the elelement is a target tag. } // the substring is in target list and update its index. indexs[hashmap[e]] = index; std::cout << e << "is found "<< " index : "<< index << std::endl; int max =0; int min =0; max = *std::max_element(indexs.begin(), indexs.end()); if ( max != INT_MAX){// all the substring in target have been found at less one time. so now can check the distance. min = *std::min_element(indexs.begin(),indexs.end()); std::cout<<"max : "<< max << " min: "<< min << std::endl; //find a more small distance. update the index and distance. if ( distance > (max - min)){ distance = max - min; ind1 = min ; ind2 = max; } } index++; } if ( distance == 0) return {0}; else return {ind1, ind2}; } int main () { // std::vector<std::string> ta = {"made", "in" , "spain"}; // std::vector<std::string> av = {"made", "weather","forecast","says","taht","made","rain","in","spain","stay"}; // std::vector<std::string> ta = {"2abc", "bcd" , "cab"}; // std::vector<std::string> av = {"dbc", "2abc","cab","bcd","bcb"}; // std::vector<std::string> ta = {"in", "the" , "spain"}; std::vector<std::string> av = {"the", "spain","that","the","rain","in","spain","stays","forcaste","in"}; auto res = subStringKDistance(av, ta); for (auto e: res) std::cout<< e << " "; return 0; }