Created
July 10, 2013 09:51
-
-
Save luoxiaoxun/5965035 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
C++: | |
class Solution { | |
private: | |
bool canUse[256]; | |
public: | |
int lengthOfLongestSubstring(string s) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
memset(canUse,true,sizeof(canUse)); | |
int start=0; | |
int count=0; | |
int ret=0; | |
for(int i=0;i<s.size();i++){ | |
if(canUse[s[i]]==true){ | |
canUse[s[i]]=false; | |
count++; | |
}else{ | |
ret=max(ret,count); | |
while(true){ | |
canUse[s[start]]=true; | |
count--; | |
if(s[start]==s[i]) break; | |
start++; | |
} | |
start++; | |
canUse[s[i]]=false; | |
count++; | |
} | |
} | |
ret=max(ret,count); | |
return ret; | |
} | |
}; | |
Java: | |
public class Solution { | |
private boolean[] canUse=new boolean[256]; | |
public int lengthOfLongestSubstring(String s) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
Arrays.fill(canUse,true); | |
int start=0; | |
int count=0; | |
int ret=0; | |
for(int i=0;i<s.length();i++){ | |
if(canUse[s.charAt(i)]){ | |
canUse[s.charAt(i)]=false; | |
count++; | |
}else{ | |
ret=Math.max(ret,count); | |
while(true){ | |
canUse[s.charAt(start)]=true; | |
count--; | |
if(s.charAt(start)==s.charAt(i)) break; | |
start++; | |
} | |
start++; | |
canUse[s.charAt(i)]=false; | |
count++; | |
} | |
} | |
ret=Math.max(ret,count); | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment