Skip to main content

rustgym/leetcode/
_806_number_of_lines_to_write_string.rs

1struct Solution;
2
3impl Solution {
4    fn number_of_lines(widths: Vec<i32>, s: String) -> Vec<i32> {
5        let mut lines = 0;
6        let mut start = 0;
7        for b in s.bytes() {
8            let w = widths[(b - b'a') as usize];
9            if start + w > 100 {
10                lines += 1;
11                start = w;
12            } else {
13                start += w;
14            }
15        }
16        vec![lines + 1, start]
17    }
18}
19
20#[test]
21fn test() {
22    let widths = vec![
23        10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
24        10, 10, 10,
25    ];
26    let s = "abcdefghijklmnopqrstuvwxyz".to_string();
27    let res = vec![3, 60];
28    assert_eq!(Solution::number_of_lines(widths, s), res);
29    let widths = vec![
30        4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
31        10, 10, 10,
32    ];
33    let s = "bbbcccdddaaa".to_string();
34    let res = vec![2, 4];
35    assert_eq!(Solution::number_of_lines(widths, s), res);
36}