LintCode1638: Least Substrig

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

你可能感兴趣的:(LintCode1638: Least Substrig)