1. 程式人生 > >[LeetCode刷題菜鳥集] 806.Number of Lines To Write String 寫字串需要的行數

[LeetCode刷題菜鳥集] 806.Number of Lines To Write String 寫字串需要的行數

我們要把給定的字串 S 從左到右寫到每一行上,每一行的最大寬度為100個單位,如果我們在寫某個字母的時候會使這行超過了100 個單位,那麼我們應該把這個字母寫到下一行。我們給定了一個數組 widths ,這個陣列 widths[0] 代表 'a' 需要的單位, widths[1] 代表 'b' 需要的單位,..., widths[25] 代表 'z' 需要的單位。

現在回答兩個問題:至少多少行能放下S,以及最後一行使用的寬度是多少個單位?將你的答案作為長度為2的整數列表返回。
示例 1:
輸入: 
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"
輸出: [3, 60]

示例 2: 
輸入: 
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] 
S = “bbbcccdddaaa” 
輸出: [2, 4] 
解釋: 
所有的字元擁有相同的佔用單位10。所以書寫所有的26個字母,
我們需要2個整行和佔用60個單位的一行。

import java.util.Arrays;
public class numberOfLines {
	public static int[] numberOfLines(int[] widths, String S) {
		int num = 0;
		int line=1;
		for(int i=0;i<S.length();i++) {
			int r = 0;
			num+=widths[S.charAt(i)-'a'];
			r+=widths[S.charAt(i)-'a'];	
			if(num>100) {
				num=0;
				line++;
				num+=r;
			}
		}
		int[] a = {line,num};
		return a;
	}
	public static void main(String[] args) {
		int[] 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};
		String	S = "abcdefghijklmnopqrstuvwxyz";
		System.out.println(Arrays.toString(numberOfLines(widths, S)));
	}