-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path[lint]. Longest Words.java
executable file
·74 lines (60 loc) · 1.41 KB
/
[lint]. Longest Words.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
E
tags: Hash Table, String, Lint
给一串String, 找到最长的长度, 把最长的String全都return
#### Hash Table
- <Integer,List<String>>
- 存最长值, 最后map.get(max)
```
/*
Given a dictionary, find all of the longest words in the dictionary.
Example
Given
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
the longest words are(is) ["internationalization"].
Given
{
"like",
"love",
"hate",
"yes"
}
the longest words are ["like", "love", "hate"].
Challenge
It's easy to solve it in two passes, can you do it in one pass?
Tags Expand
Enumeration String LintCode Copyright
Thoughts:
Two pass: 1st, get longest length. 2nd pass, get all words.
One pass:
1. Use hashmap: <lengthOfString, ArrayList<String>>
2. keep track of the longest length
*/
/*
Thoughts:
1. one pass, save in <Integer, List>.
2. Maintain max length
3. return
*/
public class Solution {
public List<String> longestWords(String[] dictionary) {
if (dictionary == null || dictionary.length == 0) {
return null;
}
Map<Integer, List<String>> map = new HashMap<>();
int max = 0;
for (String word : dictionary) {
int length = word.length();
map.putIfAbsent(length, new ArrayList<>());
map.get(length).add(word);
max = Math.max(max, length);
}
return map.get(max);
}
}
```