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;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容