3.Longest Substring Without Repeating Characters

来源:互联网 发布:端口查询 编辑:程序博客网 时间:2024/05/16 09:24

Longest Substring Without Repeating Characters

 Total Accepted: 49054 Total Submissions: 226266My Submissions

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)

代码:

class Solution {
public:
 int lengthOfLongestSubstring(string s) {  
        if(s.size()==0) return 0;
        bool exist[256];
        //初始化
        for(int i=0;i<256;++i)
            exist[i]=false;
        int start=0,end=0,char_count=0;
        while(end<s.size()){
            //遇到相同的字符,则更新结果,当前子字符串,和辅助标记数组
            if(exist[s[end]]){
                char_count=max(char_count,end-start);
                while(s[start]!=s[end]){
                    exist[s[start]]=false;
                    ++start;
                }
                ++start;
                ++end;
            }else{//否则,继续
                exist[s[end]]=true;
                ++end;
            }
        }
        return max(char_count,end-start);
    } 
};


0 0
原创粉丝点击