Solution:
Iterate through the string, and check if the current char is existed in the longest substring. If it exists, cut off the longest substring from the next char of the already existed char.
public class Solution {
public int lengthOfLongestSubstring(String s) {
int longest = 0;
char[] c = s.toCharArray();
String str = new String();
for(int i = 0; i < c.length; i++){
int pos = str.indexOf(c[i]);
if(pos > -1){ // exist
if(str.length() > longest) longest = str.length();
str = str.substring(pos+1) + c[i];
}
else str += c[i];
}
if(str.length() > longest) longest = str.length();
return longest;
}
}

No comments:
Post a Comment