-
Notifications
You must be signed in to change notification settings - Fork 2
/
ShortestCompletingWord.java
43 lines (34 loc) · 1.18 KB
/
ShortestCompletingWord.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
package com.haibo.yan.algorithm.string;
/**
* https://leetcode.com/problems/shortest-completing-word/submissions/
*/
public class ShortestCompletingWord {
public String shortestCompletingWord(String licensePlate, String[] words) {
int[] plateChars = new int[26];
int[][] wordSChars = new int[words.length][26];
for (char c : licensePlate.toLowerCase().toCharArray()) {
if (c >= 'a' && c <= 'z')
plateChars[c - 'a']++;
}
for (int i = 0; i < words.length; i++) {
for (char c : words[i].toCharArray()) {
wordSChars[i][c - 'a']++;
}
}
String candidate = null;
for (int i = 0; i < wordSChars.length; i++) {
int[] wi = wordSChars[i];
boolean isCompleted = true;
for (int j = 0; j < 26; j++) {
if (wi[j] < plateChars[j]) {
isCompleted = false;
break;
}
}
if (isCompleted && (candidate == null || words[i].length() < candidate.length())) {
candidate = words[i];
}
}
return candidate;
}
}