美文网首页
3.Longest Substring Without Repe

3.Longest Substring Without Repe

作者: swimfree | 来源:发表于2019-04-25 17:30 被阅读0次

    最长子串

    Given a string, find the length of the longest substring without repeating characters.
    
    Example 1:
    
    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    Example 2:
    
    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    代码

     public int lengthOfLongestSubstring(String s) {
            int maxLength = 0;
            String temp = "";
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(!temp.contains(c + "")){
                    temp = Strings.concat(temp,c);
                    if(temp.length() > maxLength) {
                        maxLength = temp.length();
                    }
                }else {
                    int k = temp.indexOf(c);
                    temp = temp.substring(k+1) + c;
                }
            }
            return maxLength;
        }
    

    分析

    一个变量记录当前最大长度,一个变量记录当前子串
    没找到重复的就加到当前子串上,然后跟当前记录的最大长度进行比较取最大值,
    找到重复的时候把子串重设为重复的那个字符开始取值!!

    相关文章

      网友评论

          本文标题:3.Longest Substring Without Repe

          本文链接:https://www.haomeiwen.com/subject/ynnzgqtx.html