forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShortest Completing Word.java
74 lines (64 loc) · 2.06 KB
/
Shortest Completing Word.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
HashMap<Character,Integer> plate = new HashMap<Character,Integer>();
ArrayList<String> ans = new ArrayList<>();
String str = licensePlate.toLowerCase();
for(int i=0;i<licensePlate.length();i++)
{
char c = str.charAt(i);
if(c>='a' && c<='z')
{
if(plate.containsKey(c))
{
plate.put(c,plate.get(c)+1);
}
else
{
plate.put(c,1);
}
}
}
for(int i=0;i<words.length;i++)
{
String s = words[i].toLowerCase();
HashMap<Character,Integer> wordHash = new HashMap<>();
for(int j=0;j<words[i].length();j++)
{
char c = words[i].charAt(j);
if(wordHash.containsKey(c))
{
wordHash.put(c,wordHash.get(c)+1);
}
else
{
wordHash.put(c,1);
}
}
int count = 0;
for(Map.Entry<Character,Integer> t:plate.entrySet())
{
if(wordHash.containsKey(t.getKey()))
{
if(wordHash.get(t.getKey())>=t.getValue())
{
count++;
}
}
}
if(count==plate.size())
{
ans.add(words[i]);
}
}
Comparator<String> stringLengthComparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return Integer.compare(o1.length(), o2.length());
}
};
Collections.sort(ans, stringLengthComparator);
return ans.get(0);
}
}