The longest substring without duplicate characters

Keywords: Java

Title:
Given a string, find out the length of the longest substring that does not contain duplicate characters.
Example 1:

Input: "abcabcbb"
Output: 3
Interpretation: Because the longest substring without duplicate characters is "abc", its length is 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: because the longest substring without repeating characters is "b", its length is 1.

Example 3:

Input: "pwkew"
Output: 3
Interpretation: Because the longest substring without duplicate characters is "wke", its length is 3.
Note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

Algorithm:

Method 1:

class Solution {
    public int lengthOfLongestSubstring(String s) {  
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int end = 0, start = 0; end < n; end++) {
            char alpha = s.charAt(end);
            if (map.containsKey(alpha)) {
                start = Math.max(map.get(alpha), start);
            }
            ans = Math.max(ans, end - start + 1);
            map.put(s.charAt(end), end + 1);
        }
        return ans;
    }
}

Method two:

class Solution {
    public int lengthOfLongestSubstring(String s) {  
        int max=0;
        int start=0;
        for(int i=0;i<s.length();i++)
        {
            for(int j=start;j<i;j++)
            {
                if(s.charAt(i)==s.charAt(j))
                    start=j+1;
            }
            if(max<i-start+1)
                max=i-start+1;
        }
        return max;
}

Method three:

class Solution {
    public int lengthOfLongestSubstring(String s) { 
        char[] ss=s.toCharArray();
        if(s.length()==0)
            return 0;
        int maxsize=1,start=0,end=0,same=0;
        int have=0;
        for(int i=1;i<ss.length;i++)
        {
            have=0;
            for(int j=start;j<=end;j++)
            {
                if(ss[i]==ss[j])
                {
                    have=1;
                    same=j;
                }
            }            
            if(have==1)
            {
                start=same+1;
            }
            end++;            
            if((end-start+1)>maxsize)
                maxsize=end-start+1;
        }
        return maxsize;
    }
}

Submission of records

Submission time Submit results Execution time Memory consumption language
2 days ago adopt 29 ms 39.9 MB Java
2 days ago adopt 7 ms 38 MB Java
2 days ago adopt 18 ms 38.4 MB Java

Posted by akelavlk on Sat, 12 Oct 2019 08:01:38 -0700