Longest Substring with At Least K Repeating Characters(395)

395—Longest Substring with At Least K Repeating Characters

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:
s = “aaabb”, k = 3
Output:
3
The longest substring is “aaa”, as ‘a’ is repeated 3 times.

Example 2:

Input:
s = “ababbc”, k = 2
Output:
5
The longest substring is “ababb”, as ‘a’ is repeated 2 times and ‘b’ is repeated 3 times.

C代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* substring(const char *s,int start,int end) {
  char *newStr = malloc(end - start + 1);
  int count = 0;
  for (int i = start; i< end ;i++) {
    newStr[count++] = s[i];
  }
  newStr[count] ='\0';
  return newStr;
}

int longestSubstring(char* s, int k) {
    int count[26]={0};

    int divideIndex[10000]; //存储分割点的下标
    int num = 0;

    int result = 0;

    for (int i = 0; i < strlen(s);i++) {
      count[s[i]-'a']++;
    }
    for (int i = 0; i < strlen(s);i++) {
      if(count[s[i]-'a']< k) {
        divideIndex[num++] = i;
      }
    }

    if (num == 0) {             //递归的边界条件:所有的字符都大于k次
      return strlen(s);   
    } else {
      int start = 0,end = 0, length = 0;
      for (int i = 0; i <= num;i++) { //小于k次的字母将字符串分割为(num+1)段
        if(i == 0) start = 0;         //首段的上界
        else start = divideIndex[i-1]+1;

        if ( i == num ) end = strlen(s); //最后一段的下界
        else end = divideIndex[i];

        length = longestSubstring(substring(s,start,end),k);
        if(length > result)
          result = length;
      }
    }

    return result;
}

Complexity Analysis:

Time complexity : O(nlogn).
Space complexity : O(1).

思路:

  • 分治递归思想
  • 首先小于k次的字母是不可能出现在目标串中的, 通过这些字母分割字符串, 会降低字符串的规模; 对于分割后的字符串采用同样的分割方式, 递归的边界条件是该段中所有的字符次数都大于k次.

猜你喜欢

转载自blog.csdn.net/kelly_fumiao/article/details/85070383