【Leetcode】Longest Substring Without Repeating Characters

来源:互联网 发布:js弹出选择保存路径 编辑:程序博客网 时间:2024/06/15 03:41

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.

题意:求字符串s的最大不重复字符子串的长度。

一看这题,马上就可以判断暴力破解是行不通的,于是经过仔细的思考,得出了如下的实现方式,算法复杂度为

1)定义两个指针,start和end(本题没有写出end,而是以count代替),初始时将start置为0,end置为0。并声明一个大小为256的字符数组保存s中各个字符是否已经遍历。

2)只要当前的字符s[i]未曾遍历,就将count不断加1,并在数组中将相应的字符设置为已经遍历。

3)若当前的字符已经遍历,表明这个子字符串存在重复字符,此时判断count与最优解max的大小,将max设为较大值。设这个重复字符的前后位置为pos1和pos2。那么此时将start逐步增加至pos1+1处,在这个过程中,不要忘记将对应字符数组的字符状态设为true,则表明未遍历。

4)继续2)中步骤,直到字符串结束。

5)最后不要忘记比较count和max的大小,此时的count表明位于字符串最后一部分不重复子串的长度。

代码如下:

class Solution {public:    int lengthOfLongestSubstring(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        bool canUse[256];        memset(canUse,true,sizeof(canUse));        int start=0,count=0,max=0;        for(int i=0;i<s.size();i++)        {            if(canUse[s[i]])            {                canUse[s[i]]=false;                count++;            }            else            {                if(count>max)                    max=count;                while(s[start]!=s[i])                {                    canUse[s[start]]=true;                    start++;                    count--;                }                canUse[s[start]]=false;                start++;            }        }        if(count>max)            max=count;        return max;    }};


原创粉丝点击