-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL806.java
More file actions
33 lines (33 loc) · 1.28 KB
/
L806.java
File metadata and controls
33 lines (33 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution806 {
class Solution {
/**
* 806. Number of Lines To Write String https://leetcode.com/problems/number-of-lines-to-write-string/description/
*
* @param widths int[]
* Array of widths for each character at corresponding index
* @param S String
* The input string
* @return Two sized array with first element containing number of lines and second width of last line
* @timeComplexity O(n) where n is the number of characters in input string
* @spaceComplexity O(1)
*/
public int[] numberOfLines(int[] widths, String S) {
int lineCount = 1;
int curLine = 0;
for (int i = 0; i < S.length(); i++) {
curLine += widths[S.charAt(i) - 'a'];
if (curLine > 100) {
// Didn't fit on current line
lineCount++;
// Spillover width
curLine = widths[S.charAt(i) - 'a'];
} else if (curLine == 100) {
// Begin new line
lineCount++;
curLine = 0;
}
}
return new int[]{lineCount, curLine};
}
}
}