LeetCode - LongestSubstring  

by ne on 2022-08-26 under Algo/DS/Problems tagged with leetcode

The problem belongs to LeetCode, here is the link to the problem

Following code segment contains the description in the class comments, followed by fully working solution

 

 


/**
 * Given a string s, find the length of the longest substring without repeating characters.

 * Example 1:
 * Input: s = "abcabcbb"
 * Output: 3
 * Explanation: The answer is "abc" with the length of 3.
 * 
 */
public class LongestSubstring {
    // this method is provided by leetcode , adding dummy logic here.
    public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()<=0) return 0;
        char[] arr=s.toCharArray();
        int mlen=1;
        int st=0;
        int len=0;
        int[] map = new int[256];

        Arrays.fill(map, -1);
        for(int i=0;imlen){
                    mlen=len;
                }
            }else{
                // arr[i] already exists
                int k = map[arr[i]];
                for(int p=st;p<=k;p++){
                    map[arr[p]] = 0;
                    len--;
                }
                st=k+1;
                map[arr[i]] = i;
                len++;
            }
        }
        return mlen;
    }
}