diff --git a/CMakeLists.txt b/CMakeLists.txt index a8f0aea7..a987b309 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -148,6 +148,7 @@ add_task(evaluate-division) add_task(evaluate-reverse-polish-notation) add_task(excel-sheet-column-number) add_task(excel-sheet-column-title) +add_task(extra-characters-in-a-string) add_task(factorial-trailing-zeroes) add_task(fair-distribution-of-cookies) add_task(fibonacci-number) diff --git a/solutions/extra-characters-in-a-string/CMakeLists.txt b/solutions/extra-characters-in-a-string/CMakeLists.txt new file mode 100644 index 00000000..17230694 --- /dev/null +++ b/solutions/extra-characters-in-a-string/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_extra_characters_in_a_string test.cpp) diff --git a/solutions/extra-characters-in-a-string/solution.hpp b/solutions/extra-characters-in-a-string/solution.hpp new file mode 100644 index 00000000..e7e50a5e --- /dev/null +++ b/solutions/extra-characters-in-a-string/solution.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include +#include + +class Solution { +public: + static int minExtraChar(std::string s, + const std::vector &dictionary) { + const int n = s.size(); + const std::unordered_set words{dictionary.begin(), + dictionary.end()}; + + std::vector dp(n + 1); + for (int i = 1; i <= n; ++i) { + dp[i] = n; + for (int j = 0; j < i; ++j) { + const auto extra = words.count(s.substr(j, i - j)) ? 0 : i - j; + dp[i] = std::min(dp[i], dp[j] + extra); + } + } + return dp.back(); + } +}; diff --git a/solutions/extra-characters-in-a-string/test.cpp b/solutions/extra-characters-in-a-string/test.cpp new file mode 100644 index 00000000..d85aa2d3 --- /dev/null +++ b/solutions/extra-characters-in-a-string/test.cpp @@ -0,0 +1,16 @@ +#include + +#include + +TEST_CASE("Simple") { + { + std::vector dictionary{"leet", "code", "leetcode"}; + std::string s = "leetscode"; + REQUIRE(1 == Solution::minExtraChar(s, dictionary)); + } + { + std::vector dictionary{"hello", "world"}; + std::string s = "sayhelloworld"; + REQUIRE(3 == Solution::minExtraChar(s, dictionary)); + } +}