LeetCode-3:Longest Substring Without Repeating Characters

一、題目

原題鏈接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
難度等級:中等

Given a string, find the length of the longest substring without repeating characters.

Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

題目翻譯:
給定一個字符串,找出其中無重複字符的最長子串的長度。
例如:
“abcabcbb”,無重複字符的最長子串是”abc”,長度爲3。
“bbbbb”,無重複字符的最長子串是”b”,長度爲1


二、解題方案

思路1:
通過Bitmap來統計是否子字符串中有重複的字符。遍歷時若遇到重複值,需要回溯。

代碼實現:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> m;
        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m.find(s[i]) != m.end() && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

        return maxLen;
    }
};

思路2:
通過一個數字來存儲每一個字符上一次出現的位置,當出現衝突時及時調整。

代碼實現:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        const int MAX_CHARS = 256;
        int m[MAX_CHARS];
        memset(m, -1, sizeof(m));

        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] != -1 && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

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