Skip to content

1160. Find Words That Can Be Formed by Characters 👍

  • Time: $O(n)$
  • 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
class Solution {
 public:
  int countCharacters(vector<string>& words, string chars) {
    int ans = 0;
    vector<int> count(26);

    for (const char c : chars)
      ++count[c - 'a'];

    for (const string& word : words) {
      vector<int> tempCount(count);
      for (const char c : word)
        if (--tempCount[c - 'a'] < 0) {
          ans -= word.length();
          break;
        }
      ans += word.length();
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int countCharacters(String[] words, String chars) {
    int ans = 0;
    int[] count = new int[26];

    for (final char c : chars.toCharArray())
      ++count[c - 'a'];

    for (final String word : words) {
      int[] tempCount = count.clone();
      for (final char c : word.toCharArray())
        if (--tempCount[c - 'a'] < 0) {
          ans -= word.length();
          break;
        }
      ans += word.length();
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def countCharacters(self, words: list[str], chars: str) -> int:
    ans = 0
    count = collections.Counter(chars)

    for word in words:
      tempCount = count.copy()
      for c in word:
        tempCount[c] -= 1
        if tempCount[c] < 0:
          ans -= len(word)
          break
      ans += len(word)

    return ans