Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình tìm độ dài dãy con liên tiếp có cùng chữ cái đầu trong Python

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

  1. Khởi tạo maxlength = 0, curr_letter = None, curr_length = 0.
  2. Duyệt từng từ:
    • Nếu curr_letter khác chữ cái đầu từ hiện tại: cập nhật maxlength, đặt curr_letter và curr_length = 1.
    • Ngược lại: tăng curr_length.
  3. 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