您的位置:首页 > 其它

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

2015-04-10 10:49 639 查看
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)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐