Leetcode PHP solution -- D22 806. Number of Lines To Write String

Keywords: PHP

806. Number of Lines To Write String

Title Link

806. Number of Lines To Write String

Title Analysis

Each line can only hold 100 characters, given the width of each character;

Calculates how many lines a given string takes and how many characters the last line takes.

thinking

First of all, the first line can be added directly.
When it reaches 100, the current word is written to the next line. Then the number of lines increases, when the word length is directly used as the end coordinate of the next line.

Just return the number of lines and the end coordinate of the last line.

Final code

<?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];
                                                                                                                                        }
                                                                                                                                        }
                                                                                                                                    
                                                                                                                                    If you think this article is useful to you, please use [love power generation] (https://afdian.net/@skys215) to help.
                                                                                                                                    
                                                                                                                                    

Posted by danrah on Thu, 05 Dec 2019 12:58:30 -0800