Longest Substring Without Repeating Characters

解题思路:两个指针,开始都指向字符串起始位置, 然后指针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;
    }
};


发布了60 篇原创文章 · 获赞 1 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章