[LeetCode] 806. Number of Lines To Write String

Chobby·2025년 5월 6일
1

LeetCode

목록 보기
407/427

😎풀이

  1. widths의 가중치가 적용된 배열을 생성한다.
  2. 100의 너비를 갖는 lineOfS를 갱신하며 몇 줄이 나올 수 있는지 확인한다.
  3. 최종적으로 줄 수와, 사용된 너비를 계산하여 반환한다.
function numberOfLines(widths: number[], s: string): number[] {
    const transformWidthOfS = s.split('').map(char => widths[char.charCodeAt(0) - 97])
    const initalLineWidth = 100
    let lineOfS = 1
    let curLineLeftWidth = initalLineWidth
    for(const width of transformWidthOfS) {
        if(curLineLeftWidth - width < 0) {
            lineOfS++
            curLineLeftWidth = initalLineWidth
        }
        curLineLeftWidth -= width
    }
    return [lineOfS, initalLineWidth - curLineLeftWidth]
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글