Advertisement
Guest User

Untitled

a guest
Aug 28th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. package com.strings;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. public class LongestSubstring {
  7.  
  8. public int findLongestSubstringOf2Chars(String input) {
  9. Map<Character, Integer> map = new HashMap<Character, Integer>();
  10. int curr_start = 0, curr_window_size = 1;
  11. int max_start=0, max_window_size=1;
  12. if (input.length() <= 2) return input.length();
  13.  
  14. for (int i = 0; i < input.length(); i++){
  15. char ch = input.charAt(i);
  16. if (map.containsKey(ch)){
  17. map.put(ch, map.get(ch) + 1);
  18. } else {
  19. map.put(ch, 1);
  20. }
  21.  
  22. if (map.size() > 2){
  23. curr_window_size = Math.max(curr_window_size, i - curr_start);
  24. if (curr_window_size > max_window_size){
  25. max_start = curr_start;
  26. max_window_size = curr_window_size;
  27. }
  28.  
  29. while (map.size() > 2){
  30. char temp = input.charAt(curr_start);
  31. int count = map.get(temp);
  32. if (count > 1) {
  33. map.put(temp, count - 1);
  34. } else {
  35. map.remove(temp);
  36. }
  37. curr_start++;
  38. }
  39. }
  40. }
  41.  
  42. if (curr_window_size > max_window_size){
  43. System.out.println(input.substring(curr_start, curr_start + curr_window_size));
  44. return curr_window_size;
  45. } else {
  46. System.out.println(input.substring(max_start, max_start + max_window_size));
  47. return max_window_size;
  48. }
  49.  
  50.  
  51. }
  52.  
  53. public static void main(String[] args) {
  54. LongestSubstring a = new LongestSubstring();
  55. String input1 = "aaabbbccccddee";
  56. String input2 = "abbcbcd";
  57. System.out.println(a.findLongestSubstringOf2Chars(input1));
  58. System.out.println(a.findLongestSubstringOf2Chars(input2));
  59.  
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement