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

Print Words Vertically: พิมพ์คำแนวตั้งใน Python

โจทย์

กำหนด string s ให้สร้างรายการคำอ่านแนวตั้ง (vertical) โดยคำแต่ละคำอยู่คอลัมน์เดียว คืนค่าเป็น list of strings (ไม่มี trailing spaces)

ตัวอย่าง: "HOW ARE YOU" → ["HAY", "ORO", "WEU"]

H O W
A R E
Y O U
↓ ↓ ↓
H A Y
O R O
W E U

อัลกอริทึม

  1. Split string เป็น list ของคำ (words)
  2. หา max_len = ความยาวคำที่ยาวที่สุด (จำนวนแถว)
  3. จำนวนคอลัมน์ = จำนวนคำ (len(words))
  4. สร้าง array ans ขนาด max_len เริ่มต้น empty string
  5. วนลูปแต่ละคอลัมน์ (คำ) และแต่ละแถว (ตัวอักษร):
    • ถ้าแถวปัจจุบันยาวกว่าความยาวคำ ให้เติม space
    • เพิ่มตัวอักษรลงใน ans[row]
  6. คืนค่า ans

การติดตั้ง (Python Implementation)


class Solution:
    def printVertically(self, s: str) -> list[str]:
        words = s.split()
        if not words:
            return []
        
        max_len = max(len(w) for w in words)  # จำนวนแถว
        cols = len(words)                      # จำนวนคอลัมน์
        ans = [""] * max_len
        
        for col in range(cols):
            word = words[col]
            for row in range(len(word)):
                # เติม space ถ้าแถวนี้สั้นกว่าคอลัมน์ก่อนหน้า
                while len(ans[row]) < col:
                    ans[row] += " "
                ans[row] += word[row]
        
        return ans

# ทดสอบ
ob = Solution()
print(ob.printVertically("HOW ARE YOU"))           # ['HAY', 'ORO', 'WEU']
print(ob.printVertically("TO BE OR NOT TO BE"))    # ['TBONTB', 'OEROOE', '   T']

Output

['HAY', 'ORO', 'WEU']
['TBONTB', 'OEROOE', '   T']

การทำงานของตัวอย่าง "TO BE OR NOT TO BE"

คำ:      TO   BE   OR   NOT   TO   BE
Index:   0    1    2    3     4    5

แถว 0:  T    B    O    N     T    B  → "TBONTB"
แถว 1:  O    E    R    O     O    E  → "OEROOE"
แถว 2:       (space)       T           → "   T"  (leading spaces รักษาไว้, trailing ตัดทิ้ง)

Complexity

  • Time: O(N × M) โดย N = จำนวนคำ, M = ความยาวคำเฉลี่ย
  • Space: O(N × M) สำหรับ output

สรุป

โจทย์นี้เป็นการจัดรูปแบบข้อมูล (formatting) จุดสำคัญคือการจัดการ spaces ให้ถูกต้อง: leading spaces ต้องเก็บไว้ (เพื่อ alignment) แต่ trailing spaces ต้องตัดทิ้ง (ตามเงื่อนไขโจทย์)


หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็นครับ