Skip to content

Commit 18af62e

Browse files
committed
Modified 2 solutions
1 parent e880e36 commit 18af62e

File tree

2 files changed

+63
-30
lines changed

2 files changed

+63
-30
lines changed

Easy/Longest Word in Dictionary.java

+48-13
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,51 @@
11
class Solution {
2-
public String longestWord(String[] words) {
3-
Arrays.sort(words);
4-
5-
Set<String> built = new HashSet<String>();
6-
String ans = "";
7-
8-
for (String word : words) {
9-
if (word.length() == 1 || built.contains(word.substring(0, word.length() - 1))) {
10-
ans = word.length() > ans.length() ? word : ans;
11-
built.add(word);
12-
}
13-
}
14-
return ans;
2+
Map<Integer, List<String>> map;
3+
int maxVal;
4+
public String longestWord(String[] words) {
5+
map = new HashMap<>();
6+
maxVal = Integer.MIN_VALUE;
7+
Node root = new Node('-');
8+
Arrays.sort(words);
9+
for (String word : words) {
10+
addWord(word, root, 0);
1511
}
12+
if (maxVal == Integer.MIN_VALUE) {
13+
return "";
14+
}
15+
List<String> possibleAns = map.get(maxVal);
16+
Collections.sort(possibleAns);
17+
return possibleAns.get(0);
18+
}
19+
20+
private void addWord(String word, Node root, int idx) {
21+
char c = word.charAt(idx);
22+
if (!root.children.containsKey(c) && idx != word.length() - 1) {
23+
return;
24+
}
25+
if (!root.children.containsKey(c)) {
26+
root.children.put(c, new Node(c));
27+
}
28+
root = root.children.get(c);
29+
if (idx == word.length() - 1) {
30+
root.isWord = true;
31+
int wordLength = word.length();
32+
map.computeIfAbsent(wordLength, k -> new ArrayList<>()).add(word);
33+
maxVal = Math.max(maxVal, wordLength);
34+
}
35+
else {
36+
addWord(word, root, idx + 1);
37+
}
38+
}
39+
}
40+
41+
class Node {
42+
char val;
43+
boolean isWord;
44+
Map<Character, Node> children;
45+
46+
public Node(char val) {
47+
this.val = val;
48+
isWord = true;
49+
children = new HashMap<>();
50+
}
1651
}

Medium/Contiguous Array.java

+15-17
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
class Solution {
2-
public int findMaxLength(int[] nums) {
3-
Map<Integer, Integer> map = new HashMap<>();
4-
map.put(0, -1);
5-
int maxLen = 0;
6-
int count = 0;
7-
8-
for (int i=0; i<nums.length; i++) {
9-
count += nums[i] == 0 ? -1 : 1;
10-
if (map.containsKey(count)) {
11-
maxLen = Math.max(maxLen, i-map.get(count));
12-
}
13-
else {
14-
map.put(count, i);
15-
}
16-
}
17-
18-
return maxLen;
2+
public int findMaxLength(int[] nums) {
3+
Map<Integer, Integer> map = new HashMap<>();
4+
map.put(0, -1);
5+
int maxLen = 0;
6+
int count = 0;
7+
for (int i = 0; i < nums.length; i++) {
8+
count += nums[i] == 0 ? -1 : 1;
9+
if (map.containsKey(count)) {
10+
maxLen = Math.max(maxLen, i - map.get(count));
11+
}
12+
else {
13+
map.put(count, i);
14+
}
1915
}
16+
return maxLen;
17+
}
2018
}

0 commit comments

Comments
 (0)