Longest Substring Without Repeating Characters

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.


   在做这个题的时候没有看清题目,一开始以为是选一个子序列,没通过,琢磨了一下题目,发现自己又在犯傻。

这个题目要求的是子字符串,最简单的方法是从每一个位置起始,这样要O(n * n)的复杂度

仔细想想,联想到kmp匹配可以不回头,渐渐就有这个题的思路了:每一对重复的字母把整个字符串分成了若干段,最大字字符串不可能跨段,所以当顺序发现了一对重复字符串[a1, a2]时,就可以把a1及之前的抛弃掉了,新的当前字符串从a1+1开始。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    	if(s == "")
    	{
    		return 0;
    	}
        int i;
        bool a[26];//字符已出现标记
        int p[26];//某字符上次出现位置
        for(i = 0; i < 26; i++)
        {
        	a[i] = false;
        	p[i] = -1;
        }
        int start = 0, end = 1;
        a[s[0] - 'a'] = true;
        p[s[0] - 'a'] = 0;
        int max = 1;
	int c = 1;//长度计数
        while(end < s.length())
        {
        	if(a[s[end] - 'a'] == false)
        	{
        		a[s[end] - 'a'] = true;
        		p[s[end] - 'a'] = end;
        		c++;
        	}
        	else
        	{
        		max = max > c ? max : c;
        		for(i = start; i < p[s[end] - 'a']; i++)//将被放弃部分翻转回未重复状态
        		{
        			a[s[i] - 'a'] = false;
        			p[s[i] - 'a'] = -1;
        		}
        		start = p[s[end] - 'a'] + 1;
        		p[s[end] - 'a'] = end;
        		c = end - start + 1;
        	}
        	end++;
        }
        max = max > c ? max : c;//连通到s尾部的字符串需要这个判断
        return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值