Leetcode PHP題解--D22 806. Number of Lines To Write String
806. Number of Lines To Write String
題目連結
806. Number of Lines To Write String
題目分析
每行只能容納100個字元,給定每個字元所佔寬度;
計算給定的字串需要佔多少行,最後一行佔多少個字元。
思路
首先第一行,直接新增即可。
當到達100時,當前單詞要寫到下一行。那麼行數增加,當且單詞長度直接作為下一行的末尾座標。
返回行數和最後一行的末尾座標即可。
最終程式碼
<?php class Solution { function numberOfLines($widths, $S) { $S = str_split($S); $rows = 1; $cols = 0; foreach($S as $s){ $width = $widths[ord($s)-ord('a')]; $cols += $width; if($cols>100){ $rows++; $cols = $width; } } return [$rows,$cols]; } }
若覺得本文章對你有用,歡迎用愛發電 資助。