求最长子串的长度(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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章