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.

題意:找一個字符串中,沒有重複的連續子串的最大長度。

分析:一開始想用 哈希map 來做,發現那樣就把自己搞複雜了,哈希不一定非要用map來實現,數組也可以。

其實就是一個對照關係罷了。開一個數組,記錄每個字符的最新出現位置,如果有重複,更新左值,並且更新 最大長度即可。


c++ 代碼如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        int maxlen = 0, left = 0;
        int size = s.length();
        int pre[256];
        memset(pre, -1, sizeof(pre));

        for(int i = 0; i < size; i++) {
                if(pre[s[i]] >= left) {
                        left = pre[s[i]] + 1;
                }
                pre[s[i]] = i;
                maxlen = max(maxlen, i - left + 1);
        }
        
        return maxlen;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章