Skip to content

Commit 1037a8a

Browse files
Time: 8 ms (99.43%), Space: 47.7 MB (55.68%) - LeetHub
1 parent ed140f3 commit 1037a8a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public List<List<String>> suggestedProductsTwoPointer(String[] products, String searchWord) {
3+
Arrays.sort(products);
4+
5+
int left = 0;
6+
int right = products.length - 1;
7+
8+
List<List<String>> result = new ArrayList<>();
9+
10+
for (int i = 0; i < searchWord.length(); i++) {
11+
12+
while (left <= right && (i >= products[left].length() || products[left].charAt(i) != searchWord.charAt(i))) {
13+
left++;
14+
}
15+
16+
while (left <= right && (i >= products[right].length() || products[right].charAt(i) != searchWord.charAt(i))) {
17+
right--;
18+
}
19+
List<String> currentSuggestions = new ArrayList<>();
20+
21+
for (int j = left; j <= Math.min(right, left + 2); j++) {
22+
currentSuggestions.add(products[j]);
23+
}
24+
result.add(currentSuggestions);
25+
}
26+
return result;
27+
}
28+
29+
30+
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
31+
return suggestedProductsTwoPointer(products, searchWord);
32+
}
33+
}

0 commit comments

Comments
 (0)