您的位置:首页 > 其它

LeetCode:Longest Substring Without Repeating Characters

2015-08-13 13:24 381 查看
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.

public static int lengthOfLongestSubstring(String s) {
if(s == null || s.trim().length() == 0){
return 0;
}
s = s.trim();
int len = s.length();
//char类型8位最多可表示256种字符
int[] arrayOfIndex = new int[256];
Arrays.fill(arrayOfIndex,-1);
int bIndex = 0, tmpLen = 0, maxLen = 0;
char c;
for(int i=0; i<len; i++){
c = s.charAt(i);
//发现重复字符,保证重复字符在当前子字符串内
if(arrayOfIndex[c] >= bIndex){
maxLen = maxLen > tmpLen ? maxLen : tmpLen;
//重置子字符串的起始位置,该位置有可能在上一个子字符串的内部
bIndex = arrayOfIndex[c]+1;
//重置子字符串的长度
tmpLen = i-arrayOfIndex[c]-1;
}
tmpLen++;
//记录当前字符在字符串中的位置
arrayOfIndex[c] = i;
}
return maxLen > tmpLen ? maxLen : tmpLen;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: