Longest Substring Without Repeating Characters

来源:互联网 发布:linux echo e 编辑:程序博客网 时间:2024/04/28 14:49

解题思路:两个指针,开始都指向字符串起始位置, 然后指针2向后遍历直至从pos1到pos2的子串出现重复字符,这时pos1开始自增,直至从pos1到pos2没有重复字符。

也就是遍历2遍,复杂度O(n)。

class Solution {public:    int lengthOfLongestSubstring(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int ans = 0, current_len = 0;        int pos1 = 0, pos2 = 0;        int arr[300];        memset(arr, 0, sizeof(arr));        while(pos2 < s.size())        {            if(arr[s[pos2]] == 0)            {                current_len ++ ;                arr[s[pos2]] = 1;            }            else            {                if(current_len > ans) ans = current_len;                while(s[pos1] != s[pos2])                {                    arr[s[pos1]] = 0;                    pos1 ++ ;                    current_len -- ;                }                pos1 ++ ;            }            pos2 ++ ;        }        if(current_len > ans) ans = current_len;        return ans;    }};


原创粉丝点击