-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestWordInDictionary.java
39 lines (33 loc) · 1.09 KB
/
LongestWordInDictionary.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
// https://leetcode.com/problems/longest-word-in-dictionary/
public class LongestWordInDictionary {
private final String[] input;
public LongestWordInDictionary(String[] input) {
this.input = input;
}
public String solution() {
Set<String> values = new HashSet<>();
Collections.addAll(values, input);
String result = "";
for (String word : input) {
boolean contains = true;
for (int i = 1; i < word.length(); i++) {
if (!values.contains(word.substring(0, i))) {
contains = false;
break;
}
}
if (contains) {
int rLength = result.length();
int wLength = word.length();
if (rLength < wLength || (rLength == wLength && result.compareTo(word) > 0)) {
result = word;
}
}
}
return result;
}
}