Skip to content

2707. Extra Characters in a String 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  // Similar to 139. Word Break
  int minExtraChar(string s, vector<string>& dictionary) {
    const int n = s.length();
    const unordered_set<string> dictionarySet{dictionary.begin(),
                                              dictionary.end()};
    // dp[i] := the minimum extra letters if breaking up s[0..i) optimally
    vector<int> dp(n + 1, n);
    dp[0] = 0;

    for (int i = 1; i <= n; ++i)
      for (int j = 0; j < i; ++j)
        // s[j..i) is in `dictionarySet`.
        if (dictionarySet.count(s.substr(j, i - j)))
          dp[i] = min(dp[i], dp[j]);
        // s[j..i) are extra letters.
        else
          dp[i] = min(dp[i], dp[j] + i - j);

    return dp[n];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  // Similar to 139. Word Break
  public int minExtraChar(String s, String[] dictionary) {
    final int n = s.length();
    Set<String> dictionarySet = new HashSet<>(Arrays.asList(dictionary));
    // dp[i] := the minimum extra letters if breaking up s[0..i) optimally
    int[] dp = new int[n + 1];
    Arrays.fill(dp, n);
    dp[0] = 0;

    for (int i = 1; i <= n; i++)
      for (int j = 0; j < i; j++)
        // s[j..i) is in `dictionarySet`.
        if (dictionarySet.contains(s.substring(j, i)))
          dp[i] = Math.min(dp[i], dp[j]);
        // s[j..i) are extra letters.
        else
          dp[i] = Math.min(dp[i], dp[j] + i - j);

    return dp[n];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  # Similar to 139. Word Break
  def minExtraChar(self, s: str, dictionary: List[str]) -> int:
    n = len(s)
    dictionarySet = set(dictionary)
    # dp[i] := the minimum extra letters if breaking up s[0..i) optimally
    dp = [0] + [n] * n

    for i in range(1, n + 1):
      for j in range(i):
        if s[j:i] in dictionarySet:
          dp[i] = min(dp[i], dp[j])
        else:
          dp[i] = min(dp[i], dp[j] + i - j)

    return dp[n]