We are to write the letters of a given stringS
, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths
, an array where widths[0] is the width of 'a', widths[1] is the width of 'b', ..., and widths[25] is the width of 'z'.
Now answer two questions: how many lines have at least one character fromS
, and what is the width used by the last such line? Return your answer as an integer list of length 2.
这个题依然没啥要说的,每次判断一下是不是需要换行,同时记录最后一行用了多少unit
class Solution {
public int[] numberOfLines(int[] widths, String S) {
int[] res = new int[2];
if(S == null || S.length() == 0)
return res;
int lines = 1;
int units = 0;
int limit = 100;
for(int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if(units + widths[c - 'a'] > limit) {
lines++;
units = 0;
}
units += widths[c - 'a'];
}
res[0] = lines;
res[1] = units;
return res;
}
}