3.Longest Substring Without Repeating Characters(string; DP)

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

 

思路:使用动态规划,记住当前最长 substring及开始的字符位置,这样时间复杂度最坏O(n2),最好情况下O(n)

class Solution {

public:

    int lengthOfLongestSubstring(string s) {

        if(s=="") return 0;

        

        //状态信息

        int maxLen = 1;

        int curLen = 1; 

        int startIdx = 0; 

        

        int i, j;

        for(i = 1; i < s.length(); i++){

            for(j = startIdx; j < i; j++){

                if(s[j] == s[i]){

                    //更新状态信息

                    if(curLen > maxLen) maxLen = curLen;

                    startIdx = j+1; 

                    curLen = i - startIdx + 1;

                    break;

                }

            }

            if(j == i){

                curLen++;//更新状态信息

            }

            

            if(curLen > maxLen) maxLen = curLen;//更新状态信息

        }

        return maxLen;

    }

};

 

你可能感兴趣的:(substring)