LeetCode#3.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.

思路分析

從所給的string中抽取出最長的無重複子字符串,以字符串中的每個字符作爲起始檢索,記錄遇到的每個字符,直到遇到重複的字符結束,記錄該子字符串的長度,與前面記錄的最長子字符串比較,最終得到最大值。

具體實現

在該題中的重點是記錄已經遇到過的字符,具體可採用map進行實現。
代碼如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int Max = 0;
        int length = s.size();
        for (int i = 0; i < length; ++i)
        {
            map<char, int> M;
            int j = i;
            while (j < length && M[s[j]] == 0)
            {
                M[s[j]]++;
                j++;
            }
            if ((j - i) > Max)
            {
                Max = j - i;
            }
        }
        return Max;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章