Skip to content

Commit

Permalink
Extra Characters in a String
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Sep 6, 2023
1 parent 1513736 commit 5527f5a
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions solutions/extra-characters-in-a-string/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_extra_characters_in_a_string test.cpp)
26 changes: 26 additions & 0 deletions solutions/extra-characters-in-a-string/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#pragma once

#include <algorithm>
#include <string>
#include <unordered_set>
#include <vector>

class Solution {
public:
static int minExtraChar(std::string s,
const std::vector<std::string> &dictionary) {
const int n = s.size();
const std::unordered_set<std::string> words{dictionary.begin(),
dictionary.end()};

std::vector<int> 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();
}
};
16 changes: 16 additions & 0 deletions solutions/extra-characters-in-a-string/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
std::vector<std::string> dictionary{"leet", "code", "leetcode"};
std::string s = "leetscode";
REQUIRE(1 == Solution::minExtraChar(s, dictionary));
}
{
std::vector<std::string> dictionary{"hello", "world"};
std::string s = "sayhelloworld";
REQUIRE(3 == Solution::minExtraChar(s, dictionary));
}
}

0 comments on commit 5527f5a

Please sign in to comment.