Cho văn bản text và 2 từ first, second. Tìm tất cả từ third xuất hiện ngay sau cặp "first second" (bigram). Trả về danh sách các third theo thứ tự xuất hiện.
Ví dụ: text="lina is a good girl she is a good singer", first="a", second="good" → ["girl", "singer"].
Thuật toán
- Tách văn bản thành danh sách từ:
words = text.split() - Duyệt chỉ số
itừ 0 đếnlen(words) - 3 - Nếu
words[i] == firstvàwords[i+1] == second: thêmwords[i+2]vào kết quả - Trả về kết quả
Ví dụ (Python)
class Solution(object):
def findOcurrences(self, text, first, second):
words = text.split()
res = []
for i in range(len(words) - 2):
if words[i] == first and words[i + 1] == second:
res.append(words[i + 2])
return res
ob1 = Solution()
print(ob1.findOcurrences("lina is a good girl she is a good singer", "a", "good"))
# ['girl', 'singer']
Cách khác: dùng zip (Pythonic)
def findOcurrences(text, first, second):
words = text.split()
return [w3 for w1, w2, w3 in zip(words, words[1:], words[2:])
if w1 == first and w2 == second]
Độ phức tạp
- Thời gian:
O(n)(n = số từ) - Không gian:
O(n)(danh sách từ + kết quả)
Đầu vào / Đầu ra
Input: text = "lina is a good girl she is a good singer"
first = "a", second = "good"
Output: ['girl', 'singer']