求最長子串的長度(Longest Substring Without Repeating Characters)

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.

題目描述:要求找到字符串中最長的子串的長度


代碼如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {  //
       
    int loc[128];   //以字符的值爲下標,ASCii碼錶總共是128個字符
    memset(loc,-1,sizeof(loc)); //申請sizeof(loc)個空間,並將loc數組的值都初始化爲-1
    int index=-1;   //保存子串出現的第一個位置
    int max=0;    //保存子串的長度
   
    for(int i=0;i<s.size();i++){
       if(loc[s[i]]>index){     //如果字符串s[i]出現過,則子串第一次出現的位置修改爲上一次這字符出現的位置
           index=loc[s[i]];
       } 
       if(i-index>max){    //字串的長度即爲當前下標減去子串第一個字符出現的位置,與max進行比較,
           max=i-index;
       }
       loc[s[i]]=i;      //記錄字符出現的位置
    }
    return max;
    }
};

時間複雜度爲O(n)。

發佈了22 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章