Advertisement
uopspop

Untitled

Jul 7th, 2021
1,271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param s: a string
  4.      * @param k: an integer
  5.      * @return: the number of substrings there are that contain at least k distinct characters
  6.      */
  7.     public long kDistinctCharacters(String s, int k) {
  8.         // Write your code here
  9.  
  10.  
  11.         int[] char_count = new int[26];
  12.  
  13.         long count_result = 0; // attention: use long data type here
  14.         long count_unique_char = 0;
  15.         int i_left = 0;
  16.         int i_right = -1;
  17.  
  18.         char c_now;
  19.         int i_now;
  20.  
  21.         while (true) {
  22.             if (i_right == s.length()) break;
  23.             if (i_left == s.length()) break;
  24.  
  25.             if (count_unique_char < k) {
  26.                 // not enough characters yet
  27.                 // collect char
  28.                 i_right++;
  29.                 if (i_right == s.length()) break; // attention
  30.                 c_now = s.charAt(i_right);
  31.                 i_now = c_now - 'a';
  32.  
  33.                
  34.                 if (char_count[i_now] == 0) {
  35.                     // new char inserted
  36.                     count_unique_char++;
  37.                 }
  38.  
  39.                 char_count[i_now]++;                    
  40.             }else {
  41.                 // enough characters
  42.                 count_result += (s.length() - i_right); // find answer area
  43.  
  44.                 // remove the left most to see if any better in the future
  45.                 c_now = s.charAt(i_left);
  46.                 i_now = c_now - 'a';
  47.                 char_count[i_now]--;
  48.                 if (char_count[i_now] == 0) {
  49.                     // the last char is remove for this one
  50.                     count_unique_char--;
  51.                 }                  
  52.  
  53.                 i_left++;
  54.             }
  55.  
  56.         } // end of while
  57.  
  58.         return count_result;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement