본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 806. Number of Lines To Write String

반응형

https://leetcode.com/problems/number-of-lines-to-write-string/description/

 

Number of Lines To Write String - LeetCode

Can you solve this real interview question? Number of Lines To Write String - You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

줄 개수 lines, 마지막 줄의 pixel 너비 lastLineWidth를 선언 후 각각 1과 0으로 초기화해줍니다.

📔 풀이과정

1. 문자열 s의 길이만큼 for loop를 수행합니다.

2. 두 가지의 경우에 따라 변수의 값을 수정합니다.

  2-1. 현재 너비 + lastLineWidth가 100초과시 줄이 넘어가며 lastLineWidth는 현재 너비가 됩니다.

  2-2. 아닌경우 lastLineWidth에 누적해 현재 너비를 더해줍니다.

📔 정답 출력 | 반환

lines와 lastLineWidth를 vector에 담아 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string s) {
        int lines = 1;
        int lastLineWidth = 0;
        for(auto c : s) {
            if(lastLineWidth + widths[c-'a']> 100) {
                lastLineWidth = widths[c-'a'];
                lines++;
            } else {
                lastLineWidth += widths[c-'a'];
            }
        }
        return {lines, lastLineWidth};
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.