-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUncommonWordsFromTwoSentences.java
49 lines (43 loc) · 1.46 KB
/
UncommonWordsFromTwoSentences.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.HashSet;
import java.util.Set;
// https://leetcode.com/problems/uncommon-words-from-two-sentences/
public class UncommonWordsFromTwoSentences {
private final String firstString;
private final String secondString;
public UncommonWordsFromTwoSentences(String firstString, String secondString) {
this.firstString = firstString;
this.secondString = secondString;
}
public String[] solution() {
int uniqCount = 0;
Set<String> uniq = new HashSet<>();
Set<String> duplicates = new HashSet<>();
for (String word : firstString.split(" ")) {
if (uniq.contains(word)) {
uniq.remove(word);
duplicates.add(word);
uniqCount--;
} else if (!duplicates.contains(word)) {
uniqCount++;
uniq.add(word);
}
}
for (String word : secondString.split(" ")) {
if (uniq.contains(word)) {
uniq.remove(word);
duplicates.add(word);
uniqCount--;
} else if (!duplicates.contains(word)) {
uniqCount++;
uniq.add(word);
}
}
String[] result = new String[uniq.size()];
for (String uniqWord : uniq) {
result[result.length - uniqCount] = uniqWord;
uniqCount--;
}
return result;
}
}