Skip to content

Commit

Permalink
feat(string): Add 1408
Browse files Browse the repository at this point in the history
KMP should be used for optimization..
  • Loading branch information
euchangxian committed Jan 9, 2025
1 parent 6008e38 commit 703f8a7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
33 changes: 33 additions & 0 deletions C++/1408-StringMatchingInAnArray/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <cstddef>
#include <cstdlib>
#include <string>
#include <string_view>
#include <vector>

class Solution {
public:
std::vector<std::string> stringMatching(std::vector<std::string>& 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<std::string> 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;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down

0 comments on commit 703f8a7

Please sign in to comment.