Skip to content

1078. Occurrences After Bigram

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<string> findOcurrences(string text, string first, string second) {
    vector<string> ans;
    stringstream ss(text);

    for (string prev2, prev, word; ss >> word;) {
      if (prev2 == first && prev == second)
        ans.push_back(word);
      prev2 = prev;
      prev = word;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public String[] findOcurrences(String text, String first, String second) {
    List<String> ans = new ArrayList<>();
    String[] words = text.split(" ");

    for (int i = 0; i + 2 < words.length; ++i)
      if (first.equals(words[i]) && second.equals(words[i + 1]))
        ans.add(words[i + 2]);

    return ans.toArray(new String[0]);
  }
}
1
2
3
4
class Solution:
  def findOcurrences(self, text: str, first: str, second: str) -> list[str]:
    words = text.split()
    return [c for a, b, c in zip(words, words[1:], words[2:]) if a == first and b == second]