How to find the longest substring without repeating characters in Java

1 Answer

0 votes
import java.util.Arrays;
 
public class MyClass {
    private static void findLongestSubstringWithoutRepeatingCharacters(String str) {
        int str_size = str.length();
        int start = 0, end = 0;
        int start_sub = 0, end_sub = 0;
 
        Integer [] ASCII = new Integer[256]; 
        Arrays.fill(ASCII, 0); 
 
        while (end < str_size)   {
            if (ASCII[str.charAt(end)] > 0) {
                while (str.charAt(start) != str.charAt(end)) {
                    ASCII[str.charAt(start)] = 0;
                    start++;
                }
                start++;
            }
            else {
                ASCII[str.charAt(end)] = end + 1;
                if (end - start > end_sub - start_sub) {
                    start_sub = start;
                    end_sub = end;
                }
            }
            end++;
        }
     
        for (int i = start_sub; i <= end_sub; i++) {
            System.out.print(str.charAt(i));
        }
    }
    public static void main(String args[]) {
        String str = "xwwwqfwwxqwyq";
 
        findLongestSubstringWithoutRepeatingCharacters(str);
    }
}
 
 
 
 
 
/*
run:
  
xqwy
  
*/

 



answered Mar 30, 2019 by avibootz
edited Jul 18, 2023 by avibootz
...