Longest Substring Without Repeating Characters

来源:互联网 发布:linux中查看磁盘空间 编辑:程序博客网 时间:2024/06/05 15:36

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.



用start,end两个变量来表示当前查看的起始点。首先向后扩展end,直到遇到重复的字符或者字符串结尾,然后更新最大不重复串的长度,接着从start的开始开发一直向后直到和当前end重复的那个index的后一位当作新的start开始下一次循环。 这样整个字符串处理过后就得到最长的不重复字串长度了。


class Solution {public:    int lengthOfLongestSubstring(string s) {        int len = s.length();        int start = 0, end = 0;        int ret = 0;        bool flag[256] = {false};        while (end < len) {            while (end < len && flag[s[end]] == 0) {                flag[s[end]] = true;                end++;            }            ret = max(ret, end - start);            while (start < end && s[start] != s[end]) {                flag[s[start]] = false;                start++;            }                        flag[s[start]] = false;            start++;        }                return ret;    }};


0 0