您的位置:首页 > 其它

LeetCode: Longest Substring Without Repeating Characters

2014-07-03 22:24 435 查看
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.

Solution:

public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
if(s.length() == 1) return 1;
else {
int l = 0; int r = 0;
int[] set = new int[256];
Arrays.fill(set,-1);
for(int i = 0; i < s.length(); i++){
int len = 0;
if(-1 == set[s.charAt(i)] || set[s.charAt(i)] < l){
r = i;
len = r -l+1;
set[s.charAt(i)] = i;
}else {
l = set[s.charAt(i)] + 1;
r = i;
set[s.charAt(i)] = i;
}
maxLen = Math.max(maxLen,len);
}
return maxLen;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: