Three longest substrings without repeated characters (likou net problem solving)

Likouwang problem-solving (three longest substrings without repeated characters)

Original title description:
Insert picture description here

Problem-solving code:

public class LongestSubstringWithoutRepeatingCharacters {
    
    

    public static int lengthOfLongestSubstring(String s) {
    
    
        int i = 0;
        int step = 0;
        Map<Character,Integer> con = new HashMap<>(16);
        StringBuilder str = new StringBuilder();
        StringBuilder tempStr = new StringBuilder();
        while ( i < s.length()){
    
    
            if(con.get(s.charAt(i)) != null){
    
    
                con.clear();
                if(tempStr.length() > str.length()){
    
    
                    str = tempStr;
                }
                tempStr = new StringBuilder();
                step ++;
                i = step;
            }else{
    
    
                tempStr.append(s.charAt(i));
                con.put(s.charAt(i),i);
                i++;
            }
        }
        if(tempStr.length() > str.length()){
    
    
            str = tempStr;
        }
        return str.length();
    }

    public static int lengthOfLongestSubstring2(String s) {
    
    
        Map<Character,Integer> con = new HashMap<>(16);
        StringBuilder res = new StringBuilder();
        StringBuilder str = new StringBuilder();
        int i = 0;
        while ( i < s.length()){
    
    
            char b = s.charAt(i);
            if(con.get(b) != null){
    
    
                if(res.length() < str.length()){
    
    
                    res = str;
                }
                str = new StringBuilder(str.substring(1 + str.toString().indexOf(b)));
            }else{
    
    
                con.put(b,i);
            }
            str.append(b);
            i++;
        }
        if(res.length() < str.length()){
    
    
            res = str;
        }
        return res.length();
    }


    public static void main(String[] args) {
    
    
        String s = " ";

        System.out.println(lengthOfLongestSubstring2(s));
    }

}

Guess you like

Origin blog.csdn.net/mf_yang/article/details/107226808