Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหาความยาวสับลิสต์ติดต่อมากที่สุดที่คำทุกคำขึ้นต้นด้วยตัวอักษรเดียวกันใน Python

สมมติว่ามีรายการคำที่เป็นตัวพิมพ์เล็ก เราต้องหาความยาวของสับลิสต์ติดต่อที่ยาวที่สุดที่คำทุกคำมีตัวอักษรแรกเหมือนกัน

เช่น ถ้าอินพุตคือ ["she", "sells", "seashells", "on", "the", "seashore"] ผลลัพธ์จะเป็น 3 เนื่องจากมีสามคำติดต่อ "she", "sells", "seashells" ที่ขึ้นต้นด้วย 's'

ขั้นตอนการแก้ปัญหา

  • maxlength := 0
  • curr_letter := Null, curr_length := 0
  • สำหรับแต่ละ word ใน words ทำ
    • ถ้า curr_letter เป็น null หรือ curr_letter ไม่เท่ากับ word[0] แล้ว maxlength := max(maxlength, curr_length), curr_letter := word[0], curr_length := 1
    • มิฉะนั้น curr_length := curr_length + 1
  • คืนค่า max(maxlength, curr_length)

ตัวอย่างโค้ด

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))

อินพุต

["she", "sells", "seashells", "on", "the", "seashore"]

เอาต์พุต

3