Cho danh sách từ chữ thường, tìm độ dài dãy con liên tiếp dài nhất mà tất cả từ đều có cùng chữ cái đầu.
Ví dụ
Đầu vào: ["she", "sells", "seashells", "on", "the", "seashore"].
Đầu ra: 3 (ba từ đầu tiên cùng bắt đầu bằng 's').
Thuật toán
- Khởi tạo
maxlength = 0,curr_letter = None,curr_length = 0. - Duyệt từng từ:
- Nếu
curr_letterkhác chữ cái đầu từ hiện tại: cập nhậtmaxlength, đặtcurr_lettervàcurr_length = 1. - Ngược lại: tăng
curr_length.
- Nếu
- Trả về
max(maxlength, curr_length).
Mã nguồn Python
class Solution:
def solve(self, words):
maxlength = 0
curr_letter, curr_length = None, 0
for word in words:
if not curr_letter or curr_letter != word[0]:
maxlength = max(maxlength, curr_length)
curr_letter, curr_length = word[0], 1
else:
curr_length += 1
return max(maxlength, curr_length)
ob = Solution()
words = ["she", "sells", "seashells", "on", "the", "seashore"]
print(ob.solve(words))
Đầu vào / Đầu ra
Input: ["she", "sells", "seashells", "on", "the", "seashore"]
Output: 3