806. 写字符串需要的行数『简单』

题目来源于力扣(LeetCode

一、题目

806. 写字符串需要的行数

说明:

  • 字符串 S 的长度在 [1, 1000] 的范围。
  • S 只包含小写字母。
  • widths 是长度为 26的数组。
  • widths[i] 值的范围在 [2, 10]。

二、解题思路

  1. 据题意:每一行的最大宽度为100个单位,在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行。

  2. 遍历由 S 转换成的字符数组,则当前遍历的元素的长度为 width 中的索引映射

  3. 对于已有长度 + 当前元素长度进行判断,共大于 100,等于 100,小于 100 的三种处理方式

三、代码实现

public static int[] numberOfLines(int[] widths, String S) {
    int[] nums = new int[2];
    // 记录行,初始值为 1
    int row = 1;
    // 记录行中的长度,初始值为 0
    int tail = 0;
    // 字符串长度为 1~1000,转化成字符数组更高效
    char[] arr = S.toCharArray();
    for (char i : arr) {
        // 长度 = 当前遍历元素的长度 + 当前行的长度
        int count = widths[i - 'a'] + tail;
        // 小于 100 时,往后添加长度
        if (count < 100) {
            tail = count;
        } else if (count == 100) {
            // 等于 100 时,行数加 1,重置 tail 为 0
            tail = 0;
            row += 1;
        } else {
            // 大于 100 时,行数加 1,tail 重置为当前元素的长度
            row += 1;
            tail = widths[i - 'a'];
        }
    }
    // 数组首位为 行
    nums[0] = row;
    // 数组末位为剩余长度
    nums[1] = tail;
    return nums;
}

四、执行用时

五、部分测试用例

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";  // output:{3, 60}

//    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";  // output:{2, 4}
    int[] result = numberOfLines(widths, S);
    System.out.println(Arrays.toString(result));
    }

猜你喜欢

转载自www.cnblogs.com/zhiyin1209/p/12969320.html