LintCode1638: Least Substrig

本文探讨了一个字符串分割问题,目标是最小化子字符串数量,每个子串由相同字符组成且长度不超过k。通过示例说明了如何实现这一目标,并提供了一段C++代码,展示了算法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题如下:
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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值