[LeetCode] Longest Substring Without Repeating Characters

本文介绍了一种高效算法,用于寻找给定字符串中最长的无重复字符子串,并详细解析了其实现过程及核心代码。
[Problem]
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.

[Analysis]

从头到尾遍历一次字符串,遍历过程中,用int latest[256]记录每个字母最后一次出现在字符串中的下标(初始化均为-1),用int occur[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的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值