My short Java solution


  • 1
    L

    my idea:

    1. convert the string to a chart[]. and use the "start" & "end" to locate the longest substring. 2. add char into a HashSet: every time I add the "end" char into the HashSet and move it to the next element in the array. If the "end" char is the duplicate one, I update the "max" first, and then start to remove the "start" element in the hashset until the duplicate char has been removed.
    public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null) return 0;
        int size = s.length();
        if(size == 0) return 0;
        if(size == 1) return 1;
        
        char[] array = s.toCharArray();
        int start = 0, end = 0, max = 1;
        Set sh = new HashSet();
        
        while(end<size){
            if(!sh.add(array[end])){
                if((end-start)>max) max = end-start;
                while(!sh.add(array[end])){
                    sh.remove(array[start]);
                    start = start + 1;
                }                
            }
            end = end + 1;
        }
        return max>(end-start)? max:(end-start);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.