Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. public class Main
  2. {
  3. final static int NO_OF_CHARS = 256;
  4. static int max_distinct_char(String str, int n) {
  5. int count[] = new int[NO_OF_CHARS];
  6. for (int i = 0; i < n; i++) {
  7. count[str.charAt(i)]++;
  8. }
  9. int max_distinct = 0;
  10. for (int i = 0; i < NO_OF_CHARS; i++) {
  11. if (count[i] != 0) {
  12. max_distinct++;
  13. }
  14. }
  15. return max_distinct;
  16. }
  17. static int smallesteSubstr_maxDistictChar(String str) {
  18. int n = str.length();
  19. int max_distinct = max_distinct_char(str, n);
  20. int minl = n;
  21. for (int i = 0; i < n; i++) {
  22. for (int j = 0; j < n; j++) {
  23. String subs = null;
  24. if(i<j)
  25. subs = str.substring(i, j);
  26. else
  27. subs = str.substring(j, i);
  28. int subs_lenght = subs.length();
  29. int sub_distinct_char = max_distinct_char(subs, subs_lenght);
  30. if (subs_lenght < minl && max_distinct == sub_distinct_char) {
  31. minl = subs_lenght;
  32. }
  33. }
  34. }
  35. return minl;
  36. }
  37.  
  38. public static void main(String[] args) {
  39. String str = "afshabsfjkafcnaafaf";
  40.  
  41. int len = smallesteSubstr_maxDistictChar(str);
  42. System.out.println(" The length of the smallest substring"
  43. + " consisting of maximum distinct "
  44. + "characters : "+len);
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement