Longest Substring Without Repeating Characters @LeetCode
PROBLEM :
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length()==0)
return 0 ;
int map[256] ;
int i, LastVisit, CurrLen,MaxLen ;
CurrLen=1 ;
MaxLen=1 ;
for(i=0;i<256;i++)
map[i]=-1 ;
map[s[0]]=0 ;
for(i=1;i<s.length();i++){
LastVisit=map[s[i]] ;
if(LastVisit==-1||i-CurrLen>LastVisit)
CurrLen++ ;
else{
if(CurrLen>MaxLen)
MaxLen=CurrLen ;
CurrLen=i-LastVisit ;
}
map[s[i]]=i ;
}
if(CurrLen>MaxLen)
MaxLen=CurrLen ;
return MaxLen ;
}
};
---------------------------------------------------------------------------------
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length()==0)
return 0 ;
int map[256] ;
int i, LastVisit, CurrLen,MaxLen ;
CurrLen=1 ;
MaxLen=1 ;
for(i=0;i<256;i++)
map[i]=-1 ;
map[s[0]]=0 ;
for(i=1;i<s.length();i++){
LastVisit=map[s[i]] ;
if(LastVisit==-1||i-CurrLen>LastVisit)
CurrLen++ ;
else{
if(CurrLen>MaxLen)
MaxLen=CurrLen ;
CurrLen=i-LastVisit ;
}
map[s[i]]=i ;
}
if(CurrLen>MaxLen)
MaxLen=CurrLen ;
return MaxLen ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment