-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-748-Shortest-Completing-Word.java
43 lines (36 loc) · 1.3 KB
/
LeetCode-748-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
class Solution {
// 1. Using CharArray
/*
https://leetcode.com/problems/shortest-completing-word/discuss/110137/Java-Solution-using-character-Array
Runtime: 2 ms, faster than 99.39% of Java online submissions for Shortest Completing Word.
Memory Usage: 38.7 MB, less than 100.00% of Java online submissions for Shortest Completing Word.
*/
public String shortestCompletingWord(String licensePlate, String[] words) {
licensePlate = licensePlate.toLowerCase();
int[] mask = new int[26];
for (char c : licensePlate.toCharArray()) {
if (c >= 'a' && c <= 'z') {
mask[c - 'a']++;
}
}
int minLen = Integer.MAX_VALUE;
String res = null;
for (String s : words) {
if (matches(s, mask) && s.length() < minLen) {
minLen = s.length();
res = s;
}
}
return res == null ? "" : res;
}
private boolean matches(String s, int[] mask) {
int[] sMask = new int[26];
for (char c : s.toCharArray()) {
sMask[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (mask[i] > 0 && sMask[i] < mask[i]) return false;
}
return true;
}
}