Showing posts with label longest substring wihtout repeating. Show all posts
Showing posts with label longest substring wihtout repeating. Show all posts

Sunday, 16 May 2021

Longest Substring Without Repeating Characters

 Given a string, find the length of the longest substring without repeating characters. For example, the longest

substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring

is "b", with the length of 1.


public class LongestSubstringWithoutRepeatingchar2 {

    public static void main(String[] args) {

        String str = "abcabcbd";

       // String str = "";

        int i = -1;

        int j = -1;

        Map<Character, Integer> map = new HashMap<>();

        int len = 0;


        while (true){

            boolean f1 = false, f2 = false;

            while (i<str.length()-1) {

                f1 = true;

                i++;

                char ch = str.charAt(i);

                if (map.containsKey(ch)) {

                    map.put(ch, map.get(ch) + 1);

                    break;

                } else {

                    map.put(ch, 1);

                    len = Math.max(len, i - j);

                }

            }


            while (j<i){

                f2 = true;

                j++;

                char ch = str.charAt(j);

                Integer val = map.get(ch);


                if(val>=2){

                    map.put(ch,map.get(ch)-1);

                    len = Math.max(len,i-j);

                    break;

                }else{

                    map.remove(ch);

                }

            }

            if(!f1 && !f2){

                break;

            }


        }


        System.out.println(len);




       // System.out.println(len);

    }

}


Result: 3

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...