My accepted solution in Java


  • 2
    A

    1.Give the first character of s to part.

    2.Find out the longest substring without repeating characters.

    3.return the length.

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.length()==0) return 0;
            if(s.length()==1) return 1;
            int length=0;
            String part=""+s.charAt(0);
            for(int i=1;i<s.length();i++)
            {
                if(part.indexOf(s.charAt(i))==-1)
                {
                    part=part+s.charAt(i);  
                }
                else
                {
                    int index=part.indexOf(s.charAt(i));
                    if(part.length()>length)
                    {
                        length=part.length();
                    }
                    part=part.substring(index+1);
                    i--;
                }
            }
            return part.length()>length?part.length():length;
        }
    }

  • 0
    X
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s.length() < 1)
             return 0;
            int start = 0, current, end = start + 1, longest = 1;
            while(end < s.length()){
                while(end < s.length()){
                    current = start;
                    while(current < end && s.charAt(current) != s.charAt(end))
                        current ++;
                    if(current >= end)
                        end ++;
                    else{
                        if(end - start > longest)
                            longest = end - start;
                        start = current + 1;
                        break;
                    }
                }
                if(end - start > longest)
                    longest = end - start;
            }
            return longest;
        }
    }

  • 0
    S

    could you please update your post with some explanation?


Log in to reply
 

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