原题如下:
1638. Least Substring
Given a string containing n lowercase letters, the string needs to divide into several continuous substrings, the letter in the substring should be same, and the number of letters in the substring does not exceed k, and output the minimal substring number meeting the requirement.
Example
Give s = “aabbbc”, k = 2, return 4
Explaination:
we can get “aa”, “bb”, “b”, “c” four substring.
Give s = “aabbbc”, k = 3, return 3
Explaination:
we can get “aa”, “bbb”, “c” three substring.
Notice
n ≤1e5
代码如下:
注意count 和 totalNum都初始化为1而不是0。
class Solution {
public:
/**
* @param s: the string s
* @param k: the maximum length of substring
* @return: return the least number of substring
*/
int getAns(string &s, int k) {
int len = s.size();
if (len == 0 || k < 0) return 0;
int count = 1;
int totalNum = 1;
for (int i = 1; i < len; ++i) {
if ((s[i] != s[i - 1])) {
totalNum++;
count = 1;
} else {
if (count < k) {
count++;
} else if (count == k) {
count = 1;
totalNum++;
}
}
}
return totalNum;
}
};
本文探讨了一个字符串分割问题,目标是最小化子字符串数量,每个子串由相同字符组成且长度不超过k。通过示例说明了如何实现这一目标,并提供了一段C++代码,展示了算法的具体实现过程。

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



