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.

解題思路:
這道題求解的是最大子串的長度

  1. 尋找一種容器,可以用來容納字符串,
  2. 字符串容器能夠判斷一個字符是否存在于容器中
  3. 若是字符串已經(jīng)存在于容器中,相對應(yīng)的最大子串的長度和最大子串都應(yīng)作出相應(yīng)的處理

解題代碼:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int characters[256] = {0};//保存出現(xiàn)的字符串
    int max_length = 0; // 最大子字符串長度
    int index_substring = 0;//最大子字符串的起始索引
    
    for(int i = 0; i < s.size(); i++){
        if (characters[s[i]] == 0 || characters[s[i]] < index_substring ) {
            
            //characters[s[i]] == 0 說明該字符還不存在
            //characters[s[i]] < index_substring 說明該字符已經(jīng)出現(xiàn)過,但是不在現(xiàn)在的最大子字符串里面,比如 "tmmzuxt" 中的最大子字符串是 "mzuxt" ,但是 "mzuxt" 中的 t 在第一個就出現(xiàn)過了,但是 t 在當前的最大子字符串 “mzuxt” 沒有出現(xiàn)過,所以也需要計數(shù),加入最大子字符串長度
            max_length = max(max_length, i - index_substring + 1);
        }else{
            //該字符已經(jīng)存在了,那么將更新 index_substring
            index_substring = characters[s[i]];
        }
        //給 characters[s[i]]  賦值 i+1 是為了作為最大子字符串的起始索引
        characters[s[i]] = i + 1;
    }
    return max_length;
        
    }
};

參考

  1. https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/
  2. http://www.cnblogs.com/grandyang/p/4480780.html
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容