|
39 | 39 |
|
40 | 40 | <!-- 这里可写通用的实现逻辑 -->
|
41 | 41 |
|
| 42 | +将 text 按空格切分为 words 列表,然后遍历 words,判断是否满足 `words[i] == first && words[i + 1] == second`,若是,则将 `words[i + 2]` 添加至结果列表 ans 中。 |
| 43 | + |
| 44 | +最后返回 ans 即可。 |
| 45 | + |
42 | 46 | <!-- tabs:start -->
|
43 | 47 |
|
44 | 48 | ### **Python3**
|
45 | 49 |
|
46 | 50 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
47 | 51 |
|
48 | 52 | ```python
|
49 |
| - |
| 53 | +class Solution: |
| 54 | + def findOcurrences(self, text: str, first: str, second: str) -> List[str]: |
| 55 | + words = text.split(' ') |
| 56 | + return [words[i + 2] for i in range(len(words) - 2) if words[i] == first and words[i + 1] == second] |
50 | 57 | ```
|
51 | 58 |
|
52 | 59 | ### **Java**
|
53 | 60 |
|
54 | 61 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
55 | 62 |
|
56 | 63 | ```java
|
| 64 | +class Solution { |
| 65 | + |
| 66 | + public String[] findOcurrences(String text, String first, String second) { |
| 67 | + String[] words = text.split(" "); |
| 68 | + List<String> ans = new ArrayList<>(); |
| 69 | + for (int i = 0; i < words.length - 2; ++i) { |
| 70 | + if (first.equals(words[i]) && second.equals(words[i + 1])) { |
| 71 | + ans.add(words[i + 2]); |
| 72 | + } |
| 73 | + } |
| 74 | + return ans.toArray(new String[0]); |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +``` |
| 79 | + |
| 80 | +### **C++** |
| 81 | + |
| 82 | +```cpp |
| 83 | +class Solution { |
| 84 | +public: |
| 85 | + vector<string> findOcurrences(string text, string first, string second) { |
| 86 | + istringstream is(text); |
| 87 | + vector<string> words; |
| 88 | + string word; |
| 89 | + while (is >> word) words.push_back(word); |
| 90 | + vector<string> ans; |
| 91 | + for (int i = 0; i < words.size() - 2; ++i) |
| 92 | + if (words[i] == first && words[i + 1] == second) |
| 93 | + ans.push_back(words[i + 2]); |
| 94 | + return ans; |
| 95 | + } |
| 96 | +}; |
| 97 | +``` |
57 | 98 |
|
| 99 | +### **Go** |
| 100 | +
|
| 101 | +```go |
| 102 | +func findOcurrences(text string, first string, second string) []string { |
| 103 | + words := strings.Split(text, " ") |
| 104 | + var ans []string |
| 105 | + for i := 0; i < len(words)-2; i++ { |
| 106 | + if words[i] == first && words[i+1] == second { |
| 107 | + ans = append(ans, words[i+2]) |
| 108 | + } |
| 109 | + } |
| 110 | + return ans |
| 111 | +} |
58 | 112 | ```
|
59 | 113 |
|
60 | 114 | ### **...**
|
|
0 commit comments