3. Longest Substring Without Repeating Characters

标签: DP


Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Subscribe to see which companies asked this question

有点像回文串,f[i] 表示以 i 结尾的子串最长匹配括号,转移方程是:
f[i] = 2 + f[i-1] if s[i] = ‘)’ and s[i-f[i-1]-1]=’(’+ f[i-f[i]]

( ( ) ( ) ) ( )
0 0 2 0 4 6 0 8
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int pos[256];
        for(int index = 0; index < 256; index++){
            pos[index] = -1;
        }
        
        int start = 0;
        int ret = 0;
        
        for(int index = 0; index < s.length(); index++){
            if(pos[s[index]] >= start){
                start = pos[s[index]] + 1;
            }
            
            pos[s[index]] = index;
            
            ret = max(ret, index - start + 1);
        }
        
        return ret;
    }
};

你可能感兴趣的:(3. Longest Substring Without Repeating Characters)