classSolution { public: vector<string> findOcurrences(string text, string first, string second){ vector<string> words; int s = 0, e = 0, len = text.length(); while (true) { while (s < len && text[s] == ' ') { s++; } if (s >= len) { break; } e = s + 1; while (e < len && text[e] != ' ') { e++; } words.push_back(text.substr(s, e - s)); s = e + 1; } vector<string> ret; for (int i = 2; i < words.size(); i++) { if (words[i - 2] == first && words[i - 1] == second) { ret.push_back(words[i]); } } return ret; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public String[] findOcurrences(String text, String first, String second) { String[] words = text.split(" "); List<String> list = newArrayList<String>(); for (inti=2; i < words.length; i++) { if (words[i - 2].equals(first) && words[i - 1].equals(second)) { list.add(words[i]); } } intsize= list.size(); String[] ret = newString[size]; for (inti=0; i < size; i++) { ret[i] = list.get(i); } return ret; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { publicstring[] FindOcurrences(string text, string first, string second) { string[] words = text.Split(" "); IList<string> list = new List<string>(); for (int i = 2; i < words.Length; i++) { if (words[i - 2].Equals(first) && words[i - 1].Equals(second)) { list.Add(words[i]); } } int size = list.Count; string[] ret = newstring[size]; for (int i = 0; i < size; i++) { ret[i] = list[i]; } return ret; } }
[sol1-Python3]
1 2 3 4
classSolution: deffindOcurrences(self, text: str, first: str, second: str) -> List[str]: words = text.split() return [words[i] for i inrange(2, len(words)) if words[i - 2] == first and words[i - 1] == second]
[sol1-Golang]
1 2 3 4 5 6 7 8 9
funcfindOcurrences(text, first, second string) (ans []string) { words := strings.Split(text, " ") for i := 2; i < len(words); i++ { if words[i-2] == first && words[i-1] == second { ans = append(ans, words[i]) } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var findOcurrences = function(text, first, second) { const words = text.split(" "); const list = []; for (let i = 2; i < words.length; i++) { if (words[i - 2] === first && words[i - 1] === second) { list.push(words[i]); } } const size = list.length; const ret = Array(size).fill(''); for (let i = 0; i < size; i++) { ret[i] = list[i]; } return ret; };
复杂度分析
时间复杂度:O(N),其中 N 为 text 的长度。分割 text 需要 O(N),words 每个元素最多访问两次,需要 O(N),所以总的时间复杂度为 O(N)。