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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章