806.写字符串需要的行数
链接:806.写字符串需要的行数
难度:Easy
标签:数组、字符串
简介:至少多少行能放下 S,以及最后一行使用的宽度是多少个单位?。
题解 1 - cpp
- 编辑时间:2022-04-12
- 内存消耗:6.8MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string s) {
        int surplus = 100, line = 1;
        for (auto &ch : s) {
            int cnt = widths[ch - 'a'];
            if (cnt > surplus) {
                surplus = 100;
                line++;
            }
            surplus -= cnt;
        }
        return {line, 100 - surplus};
    }
};
题解 2 - cpp
- 编辑时间:2022-03-19
- 内存消耗:6.6MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
   public:
    vector<int> numberOfLines(vector<int>& widths, string s) {
        int line = 1, surplus = 100;
        for (auto& ch : s) {
            int width = widths[ch - 'a'];
            if (surplus < width) {
                line++;
                surplus = 100;
            }
            surplus -= width;
        }
        vector<int> ans = {line, 100 - surplus};
        return ans;
    }
};