We are to write the letters of a given string S, 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 from S, and what is the width used by the last such line? Return your answer as an integer list of length 2.
题解:
package com.leetcode;
public class WritingString {
public static void main(String[] args) {
int[] widths = { 4, 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 };
String S = "bbbcccdddaaa";
int[] ans = numberOfLines(widths, S);
System.out.println(ans[0] + ", " + ans[1]);
}
public static int[] numberOfLines(int[] widths, String S) {
if (S.isEmpty())
return new int[] { 0, 0 };
int lines = 1;
int curr_widths = 0;
for (int i = 0; i < S.length(); i++) {
curr_widths += widths[S.charAt(i) - 'a'];
if (curr_widths > 100) {
lines++;
curr_widths = 0;
i--;
}
}
return new int[] { lines, curr_widths };
}
}