diff --git a/C++/1408-StringMatchingInAnArray/Solution.cpp b/C++/1408-StringMatchingInAnArray/Solution.cpp new file mode 100644 index 0000000..ed78af6 --- /dev/null +++ b/C++/1408-StringMatchingInAnArray/Solution.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include + +class Solution { + public: + std::vector stringMatching(std::vector& words) { + // Return all words that is a substring of another word. + // Naively, O(n^2 * L^2), compare each string with every other string in + // O(L^2) time. + // Can we do better? + // KMP... instead of naive string matching. + std::vector result; + result.reserve(words.size()); + for (int i = 0; i < words.size(); ++i) { + for (int j = 0; j < words.size(); ++j) { + if (i == j) { + continue; + } + + std::string_view curr{words[i]}; + std::string_view next{words[j]}; + if (next.contains(curr)) { + result.emplace_back(words[i]); + break; // Only want to push this word once. + } + } + } + return result; + } +}; diff --git a/README.md b/README.md index 727234b..1bd19cc 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,7 @@ Now solving in C++. Like it. | 1395 | CountNumberOfTeams | [![C++](assets/c++.svg)](C++/1395-CountNumberOfTeams/Solution.cpp) | | 1404 | NumberOfStepsToReduceANumberInBinaryRepresentationToOne | [![C++](assets/c++.svg)](C++/1404-NumberOfStepsToReduceANumberInBinaryRepresentationToOne/Solution.cpp) | | 1405 | LongestHappyString | [![C++](assets/c++.svg)](C++/1405-LongestHappyString/Solution.cpp) | +| 1408 | StringMatchingInAnArray | [![C++](assets/c++.svg)](C++/1408-StringMatchingInAnArray/Solution.cpp) | | 1422 | MaximumScoreAfterSplittingAString | [![C++](assets/c++.svg)](C++/1422-MaximumScoreAfterSplittingAString/Solution.cpp) | | 1423 | MaximumPointsYouCanObtainFromCards | [![C++](assets/c++.svg)](C++/1423-MaximumPointsYouCanObtainFromCards/Solution.cpp) | | 1427 | PerformStringShifts | [![C++](assets/c++.svg)](C++/1427-PerformStringShifts/Solution.cpp) |