[leetcode] 3.Longest Substring Without Repeating Characters

題目:
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.
題意:
給定一個字符串,找出字符串中最長的子串的長度,該子串中所有字符不重複。
思路:
依舊使用兩個指針,初始化的時候兩個指針都指向第一個字符,然後使用表記錄所遇到的字符出現的下標,如果第二個指針掃描到字符s[i]已經在表中出現過了,那麼記錄此時的子串的長度。讓第一個指針往前走,走到表中s[i]字符對應的下標。並且第一個指針往前走的過程中,掃描到的字符需要在表中去掉位置信息,相當於“出棧”了,告訴第二個指針這些字符沒出現過。

代碼如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.empty())return 0;
        int table[256];
        memset(table, -1, sizeof(table));
        int first = 0, second = 0, length = s.length();
        int m = 0;
        while (second < length) {
            if (table[s[second]] == -1) {
                table[s[second]] = second;
            }
            else {
                m = max(m, second - first);
                while (first <= table[s[second]]) {
                    table[s[first]] = -1;
                    first++;
                }
                table[s[second]] = second;
            }
            second++;
        }
        m = max(m, second - first);
        return m;
    }
};
發佈了239 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章