题目来源
题目描述
题目解析
我们从左到右遍历字符串 S 中的每个字母,并用二元组 (lines, width) 实时统计当前的答案。当遍历到一个字母 x 时,如果 width + widths[x] <= 100,那么就更新 width 并保持 lines 不变;如果 width + widths[x] > 100,那么就将 lines 的值加 1,并将 width 置为 widths[x]
class Solution {
public:
vector<int> numberOfLines(vector<int>& widths, string s) {
static int WIDTH = 100;
int cnt = 0, line = 1;
for(auto & ch : s){
cnt += widths[ch - 'a'];
if(cnt > WIDTH){
line++;
cnt = widths[ch - 'a'];
}
}
return {line, cnt};
}
};