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

Number of Lines To Write String ใน Python: นับบรรทัดและความกว้างสุดท้าย

มีสตริง S และอาร์เรย์ widths ที่ widths[0] = ความกว้างของ 'a', widths[1] = 'b', ... เขียนตัวอักษรจากซ้ายไปขวา แต่ละบรรทัดกว้างสูงสุด 100 หน่วย หากเกิน → ขึ้นบรรทัดใหม่ ต้องการหา (1) จำนวนบรรทัดที่มีตัวอักษร (2) ความกว้างที่ใช้ในบรรทัดสุดท้าย

ตัวอย่าง

widths = [4,10,10,...] (a=4, อื่นๆ=10), S = "bbbcccdddaaa" → [2, 4] บรรทัดแรกเขียน 9 ตัวอักษร (9×10=90) + 'a' 2 ตัว (2×4=8) รวม 98 เหลือ 2 หน่วย 'a' ตัวสุดท้ายเขียนบรรทัดใหม่กว้าง 4

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

  1. line = 1, count = 0
  2. วนแต่ละตัวอักษร c ใน S:
    • count += widths[ord(c) - 97]
    • ถ้า count > 100: line += 1, count = widths[ord(c) - 97]
  3. คืน [line, count]

การติดตั้งใน Python

class Solution:
    def numberOfLines(self, widths, S):
        line = 1
        count = 0
        for ch in S:
            w = widths[ord(ch) - 97]
            count += w
            if count > 100:
                line += 1
                count = w
        return [line, count]

ob = Solution()
print(ob.numberOfLines([4]+[10]*25, "bbbcccdddaaa"))  # [2, 4]

อินพุต / เอาต์พุต

Input: widths=[4,10,...], S="bbbcccdddaaa"
Output: [2, 4]