fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. //abcabcdbd
  11. //Sliding window solution Time: O(n), Space: O(1)
  12.  
  13. public static void main (String[] args) throws java.lang.Exception
  14. {
  15. System.out.println(getLongestStringWithoutRepetitions("abcabcdbd"));
  16. System.out.println(getLongestStringWithoutRepetitions(""));
  17. System.out.println(getLongestStringWithoutRepetitions("aaabbb"));
  18. System.out.println(getLongestStringWithoutRepetitions("aaa"));
  19. System.out.println(getLongestStringWithoutRepetitions("abc"));
  20. System.out.println(getLongestStringWithoutRepetitions("abbcdecb"));
  21. }
  22.  
  23. private static int getLongestStringWithoutRepetitions(String input) {
  24. int start=0, end=0, result=0;
  25. int[] count = new int[26];
  26. while(end<input.length()) {
  27. count[(int)(input.charAt(end)-'a')]++;
  28. if(count[(int)(input.charAt(end)-'a')]>1) {
  29. while(start<=end) {
  30. start++;
  31. count[(int)(input.charAt(start-1)-'a')]--;
  32.  
  33. if(count[(int)(input.charAt(start-1)-'a')]==1) {
  34. break;
  35. }
  36. }
  37. }
  38. result = Math.max(result, end-start+1);
  39. end++;
  40. }
  41. return result;
  42. }
  43. }
Success #stdin #stdout 0.09s 54680KB
stdin
Standard input is empty
stdout
4
0
2
1
3
4