-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathUncommonWords.java
42 lines (41 loc) · 1.3 KB
/
UncommonWords.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
/*https://leetcode.com/problems/uncommon-words-from-two-sentences/*/
class Solution {
public String[] uncommonFromSentences(String s1, String s2) {
HashMap<String,Boolean> map = new HashMap<String,Boolean>();
String[] tokens = s1.split(" ");
int falseCount = 0;
for (int i = 0; i < tokens.length; ++i)
{
if (map.containsKey(tokens[i]))
{
if ((Boolean)map.get(tokens[i]))
++falseCount;
map.put(tokens[i],false);
}
else
map.put(tokens[i],true);
}
tokens = s2.split(" ");
for (int i = 0; i < tokens.length; ++i)
{
if (map.containsKey(tokens[i]))
{
if ((Boolean)map.get(tokens[i]))
++falseCount;
map.put(tokens[i],false);
}
else
map.put(tokens[i],true);
}
String[] result = new String[map.size()-falseCount];
int i = 0;
Iterator iter = map.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry elem = (Map.Entry)iter.next();
if ((Boolean)elem.getValue())
result[i++] = (String)elem.getKey();
}
return result;
}
}