Skip to content

Commit cc08eab

Browse files
solvescheck whether two strings are almost equivalent
1 parent e202c82 commit cc08eab

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@
491491
| 2053 | [Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array) | [![Java](assets/java.png)](src/KthDistinctStringInAnArray.java) | |
492492
| 2057 | [Smallest Index With Equal Value](https://leetcode.com/problems/smallest-index-with-equal-value) | [![Java](assets/java.png)](src/SmallestIndexWithEqualValue.java) | |
493493
| 2062 | [Count Vowel Substrings of a String](https://leetcode.com/problems/count-vowel-substrings-of-a-string) | [![Java](assets/java.png)](src/CountVowelSubstringsOfAString.java) | |
494-
| 2068 | [Check Whether Two Strings are Almost Equivalent](https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent) | | |
494+
| 2068 | [Check Whether Two Strings are Almost Equivalent](https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent) | [![Java](assets/java.png)](src/CheckWhetherTwoStringsAreAlmostEquivalent.java) | |
495495
| 2073 | [Time Needed to Buy Tickets](https://leetcode.com/problems/time-needed-to-buy-tickets) | | |
496496
| 2078 | [Two Furthest Houses With Different Colors](https://leetcode.com/problems/two-furthest-houses-with-different-colors) | | |
497497
| 2085 | [Count Common Words With One Occurrence](https://leetcode.com/problems/count-common-words-with-one-occurrence) | | |

Diff for: src/CheckWhetherTwoStringsAreAlmostEquivalent.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent
2+
// T: O(|word1| + |word2|)
3+
// S: O(1)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class CheckWhetherTwoStringsAreAlmostEquivalent {
9+
public boolean checkAlmostEquivalent(String word1, String word2) {
10+
final Map<Character, Integer> word1Frequencies = getFrequencies(word1);
11+
final Map<Character, Integer> word2Frequencies = getFrequencies(word2);
12+
for (char c = 'a' ; c <= 'z' ; c++) {
13+
if (Math.abs(word1Frequencies.getOrDefault(c, 0) - word2Frequencies.getOrDefault(c, 0))
14+
> 3) {
15+
return false;
16+
}
17+
}
18+
return true;
19+
}
20+
21+
private Map<Character, Integer> getFrequencies(String s) {
22+
final Map<Character, Integer> frequencies = new HashMap<>();
23+
for (int i = 0 ; i < s.length() ; i++) {
24+
frequencies.put(s.charAt(i), frequencies.getOrDefault(s.charAt(i), 0) + 1);
25+
}
26+
return frequencies;
27+
}
28+
}

0 commit comments

Comments
 (0)