|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -import java.util.ArrayList; |
4 |
| -import java.util.List; |
| 3 | +import java.util.stream.Collectors; |
| 4 | +import java.util.stream.IntStream; |
5 | 5 |
|
6 | 6 | /**
|
7 | 7 | * 5083. Occurrences After Bigram
|
8 |
| - * |
| 8 | + * <p> |
9 | 9 | * Given words first and second, consider occurrences in some text of the form "first second third",
|
10 | 10 | * where second comes immediately after first, and third comes immediately after second.
|
11 | 11 | * For each such occurrence, add "third" to the answer, and return the answer.
|
12 |
| - * |
| 12 | + * <p> |
13 | 13 | * Example 1:
|
14 | 14 | * Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
|
15 | 15 | * Output: ["girl","student"]
|
16 |
| - * |
| 16 | + * <p> |
17 | 17 | * Example 2:
|
18 | 18 | * Input: text = "we will we will rock you", first = "we", second = "will"
|
19 | 19 | * Output: ["we","rock"]
|
20 |
| - * |
| 20 | + * <p> |
21 | 21 | * Note:
|
22 | 22 | * 1 <= text.length <= 1000
|
23 | 23 | * text consists of space separated words, where each word consists of lowercase English letters.
|
24 | 24 | * 1 <= first.length, second.length <= 10
|
25 | 25 | * first and second consist of lowercase English letters.
|
26 |
| - * */ |
| 26 | + */ |
27 | 27 | public class _5083 {
|
28 | 28 | public static class Solution1 {
|
29 | 29 | public String[] findOcurrences(String text, String first, String second) {
|
30 |
| - List<String> result = new ArrayList<>(); |
31 | 30 | String[] words = text.split(" ");
|
32 |
| - for (int i = 0; i < words.length - 2; i++) { |
33 |
| - if (words[i].equals(first) && words[i + 1].equals(second)) { |
34 |
| - result.add(words[i + 2]); |
35 |
| - } |
36 |
| - } |
37 |
| - String[] occ = new String[result.size()]; |
38 |
| - for (int i = 0; i < result.size(); i++) { |
39 |
| - occ[i] = result.get(i); |
40 |
| - } |
41 |
| - return occ; |
| 31 | + return IntStream |
| 32 | + .range(0, words.length - 2) |
| 33 | + .filter(i -> words[i].equals(first) && words[i + 1].equals(second)) |
| 34 | + .mapToObj(i -> words[i + 2]) |
| 35 | + .collect(Collectors.toList()) |
| 36 | + .stream() |
| 37 | + .toArray(String[]::new); |
42 | 38 | }
|
43 | 39 | }
|
44 | 40 | }
|
0 commit comments