- Date : 2021.12.05(일)
- Time : 25분
- 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 'a', widths[1] is the width of 'b', and so on.
- You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.
- Return an array result of length 2 where:
- result[0] is the total number of lines.
- result[1] is the width of the last line in pixels.
- widths.length == 26
- 2 <= widths[i] <= 10
- 1 <= s.length <= 1000
- s contains only lowercase English letters.
- Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"
- Output: [3,60]
- Explanation: You can write s as follows:
abcdefghij // 100 pixels wide klmnopqrst // 100 pixels wide uvwxyz // 60 pixels wide There are a total of 3 lines, and the last line is 60 pixels wide.
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
lines = 1
lastPixels = 0
for char in s:
pixel = widths[ord(char)-ord('a')]
if lastPixels + pixel > 100:
lines += 1
lastPixels = 0
lastPixels += pixel
return [lines, lastPixels]: 이 문제도 804번 문제와 비슷했다. 각 문자마다 픽셀(너비)가 주어진다. 그래서 문자를 먼저 픽셀로 바꿔준다. 근데 픽셀이 100이 넘는다면 줄 수가 늘어난다. 결국 마지막 리턴 값은 총 줄 수 와 마지막 줄의 픽셀 수를 리턴해야 한다. 여기서도 ord() 함수를 이용해 유니코드 값을 이용해주었다. 계속 문자의 픽셀 값을 lastPixels 이라는 변수에 더해주다가 이 변수가 100이 넘으면 줄 수에 +1을 해주고 lastPixels를 리셋해주었다. 마지막 줄의 픽셀을 나타내기 위해서다. 그래서 마지막에 줄 수와 lastPixels 변수를 리턴해주면 된다.