Advertisement
1988coder

395. Longest Substring with At Least K Repeating Characters

Dec 28th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. /**
  2.  * Sliding Window
  3.  *
  4.  * Time Complexity: O(26 * N)
  5.  *
  6.  * Space Complexity: O(26) = O(1)
  7.  *
  8.  * N = Length of the input string S.
  9.  */
  10. class Solution {
  11.     public int longestSubstring(String s, int k) {
  12.         if (s == null || s.length() == 0 || s.length() < k) {
  13.             return 0;
  14.         }
  15.         if (k <= 1) {
  16.             return s.length();
  17.         }
  18.  
  19.         int maxResult = 0;
  20.         int[] counts = new int[26];
  21.         int maxTarget = Math.min(26, s.length());
  22.  
  23.         for (int target = 1; target <= maxTarget; target++) {
  24.             Arrays.fill(counts, 0);
  25.             int start = 0;
  26.             int end = 0;
  27.             int uniqueChars = 0;
  28.             int charsNoLessThanK = 0;
  29.  
  30.             while (end < s.length()) {
  31.                 int endChar = s.charAt(end) - 'a';
  32.                 if (counts[endChar] == 0) {
  33.                     uniqueChars++;
  34.                 }
  35.                 counts[endChar]++;
  36.                 if (counts[endChar] == k) {
  37.                     charsNoLessThanK++;
  38.                 }
  39.                 end++;
  40.  
  41.                 while (uniqueChars > target) {
  42.                     int startChar = s.charAt(start) - 'a';
  43.                     if (counts[startChar] == k) {
  44.                         charsNoLessThanK--;
  45.                     }
  46.                     counts[startChar]--;
  47.                     if (counts[startChar] == 0) {
  48.                         uniqueChars--;
  49.                     }
  50.                     start++;
  51.                 }
  52.  
  53.                 // if we found a string where the number of unique chars equals our target and
  54.                 // all those chars are repeated at least K times then update max
  55.                 if (uniqueChars == target && uniqueChars == charsNoLessThanK) {
  56.                     maxResult = Math.max(maxResult, end - start);
  57.                 }
  58.             }
  59.         }
  60.  
  61.         return maxResult;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement