Advertisement
Guest User

Untitled

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