Sword Finger Offer Interview Question 48: The longest substring without repeated characters (dynamic programming, more abstract)

This question says to use dynamic programming, but it is actually quite abstract. The dynamic programming idea of ​​this problem is to set the function f(i) to represent the length of the largest non-repeated substring with the i-th letter as the last character. Go forward again, save the length of the difference between the last occurrence of this character and this time, and then classify and discuss. If this length is greater than the maximum length ending with the previous character, it means that the maximum length ending with the current character is above One character is the maximum length of the end plus one. If the length is less than the maximum length at the end of the previous character. The maximum length ending with the current character is the length of the difference between the last occurrence of this character and the current occurrence.

 

 

 

 

 

 

 

    public int lengthOfLongestSubstring(String s) {
        char[] char_array = s.toCharArray();
        int[] length_array = new int[char_array.length];
        int max_num = 0;
        for(int count = 0;count<char_array.length;count++){
            length_array[count] = 0;
        }

        for(int count = 0; count<char_array.length;count++){
            if(count != 0){
                int count_inner = 1;
                for(;count_inner <= s.length();count_inner++){
                    if(count - count_inner < 0){
                        break;
                    }
                    if(char_array[count]==char_array[count-count_inner]){
                        length_array[count] = count_inner;
                        break;
                    }
                }


                if(count_inner<=length_array[count-1]){
                    length_array[count] = count_inner;
                }else{
                    length_array[count]=length_array[count-1] + 1;
                }
            }else{
                length_array[count] = 1;
            }
        }
        for(int count = 0;count<length_array.length;count++){
            if(length_array[count] > max_num){
                max_num = length_array[count];
            }
        }

        return max_num;
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/114585221