Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.strings;
- import java.util.HashMap;
- import java.util.Map;
- public class LongestSubstring {
- public int findLongestSubstringOf2Chars(String input) {
- Map<Character, Integer> map = new HashMap<Character, Integer>();
- int curr_start = 0, curr_window_size = 1;
- int max_start=0, max_window_size=1;
- if (input.length() <= 2) return input.length();
- for (int i = 0; i < input.length(); i++){
- char ch = input.charAt(i);
- if (map.containsKey(ch)){
- map.put(ch, map.get(ch) + 1);
- } else {
- map.put(ch, 1);
- }
- if (map.size() > 2){
- curr_window_size = Math.max(curr_window_size, i - curr_start);
- if (curr_window_size > max_window_size){
- max_start = curr_start;
- max_window_size = curr_window_size;
- }
- while (map.size() > 2){
- char temp = input.charAt(curr_start);
- int count = map.get(temp);
- if (count > 1) {
- map.put(temp, count - 1);
- } else {
- map.remove(temp);
- }
- curr_start++;
- }
- }
- }
- if (curr_window_size > max_window_size){
- System.out.println(input.substring(curr_start, curr_start + curr_window_size));
- return curr_window_size;
- } else {
- System.out.println(input.substring(max_start, max_start + max_window_size));
- return max_window_size;
- }
- }
- public static void main(String[] args) {
- LongestSubstring a = new LongestSubstring();
- String input1 = "aaabbbccccddee";
- String input2 = "abbcbcd";
- System.out.println(a.findLongestSubstringOf2Chars(input1));
- System.out.println(a.findLongestSubstringOf2Chars(input2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement