解题思路:
简单的直接遍历,阈值溢出并计数。
代码:
class Solution {
public:
vector<int> numberOfLines(vector<int>& widths, string s) {
vector<int> ans = {1, 0};
for(auto ch : s)
{
if(ans[1] + widths[ch - 'a'] > 100) {
ans[1] = widths[ch - 'a'];
ans[0]++;
}
else ans[1] += widths[ch - 'a'];
}
return ans;
}
};
时间复杂度O(n),空间复杂度O(1)。n为字符串长度。
本文介绍了一种简单的算法,通过遍历输入字符串,计算每个字符对应的宽度,并根据阈值更新答案。此方法适用于计算字符串在给定宽度限制下的行数,时间复杂度为O(n),空间复杂度极低。
663

被折叠的 条评论
为什么被折叠?



