1. 程式人生 > >Longest Substring with At Least K Repeating Characters(395)

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次.