Skip to content

2068. Check Whether Two Strings are Almost Equivalent 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  bool checkAlmostEquivalent(string word1, string word2) {
    vector<int> count(26);

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

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

    return ranges::all_of(count, [](int freq) { return abs(freq) <= 3; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public boolean checkAlmostEquivalent(String word1, String word2) {
    int[] count = new int[26];

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

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

    return Arrays.stream(count).allMatch(freq -> Math.abs(freq) <= 3);
  }
}
1
2
3
4
5
class Solution:
  def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
    count = collections.Counter(word1)
    count.subtract(collections.Counter(word2))
    return all(abs(freq) <= 3 for freq in count.values())