[LeetCode] Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝介入后卖家不举证 编辑:程序博客网 时间:2024/06/06 20:22
[Problem]
Given a string, find the length of the longest substring withoutrepeating characters. For example, the longest substring withoutrepeating letters for "abcabcbb" is "abc", which the length is 3.For "bbbbb" the longest substring is "b", with the length of1.

[Analysis]

从头到尾遍历一次字符串,遍历过程中,用intlatest[256]记录每个字母最后一次出现在字符串中的下标(初始化均为-1),用intoccur[i]记录遍历到第i个字符时,以该字符为结尾的最长不重复子串的开头,则occur[i] = max{occur[i-1],latest[s[i]]},并更新latest[s[i]] = i。

例如abcabcde,初始化latest[256]={-1}
(1)i=0
s[i]='a',latest['a']=-1,则occur[0]=-1,更新latest['a']=0
(2)i=1
s[i]='b',latest['b']=-1,则occur[1]=-1,更新latest['b']=1
(3)i=2
s[i]='c',latest['c']=-1,则occur[2]=-1,更新latest['c']=2
(4)i=3
s[i]='a',latest['a']=0,取latest['a']与occur[3-1]中大的,则occur[3]=0,更新latest['a']=3
(5)i=4
s[i]='b',latest['b']=1,取latest['b']与occur[4-1]中大的,则occur[4]=1,更新latest['b']=4
(6)i=5
s[i]='c',latest['c']=2,取latest['c']与occur[5-1]中大的,则occur[5]=2,更新latest['c']=5
(7)i=6
s[i]='d',latest['d']=-1,取latest['d']与occur[6-1]中大的,则occur[6]=2,更新latest['d']=6
(8)i=7
s[i]='e',latest['e']=-1,取latest['e']与occur[7-1]中大的,则occur[7]=2,更新latest['e']=7

最后,遍历occur[i],取i-occur[i]最大的作为最长不重复子串的长度。


[Solution]

class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// empty string
int len = s.length();
if(len == 0){
return 0;
}

// the latest occur of each character
int latest[256];
memset(latest, -1, sizeof(latest));

// the latest occur of each position
int occur[len];
for(int i = 0; i < len; ++i){
if(i == 0){
occur[i] = latest[s[i]];
}
else{
occur[i] = latest[s[i]] > occur[i-1] ? latest[s[i]] : occur[i-1];
}
latest[s[i]] = i;
}

// get longest
int longest = 0;
for(int i = 0; i < len; ++i){
longest = longest > i - occur[i] ? longest : i - occur[i];
}
return longest;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
阅读全文
0 0
原创粉丝点击