您的位置:首页 > 编程语言 > Java开发

LeetCode | Longest Substring Without Repeating Characters

2014-04-08 14:52 363 查看
题目

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.

分析

在遍历过程中,记录各个字符最后出现位置,如果子串出现重复字符,就移动子串的起始位置。

代码

import java.util.Arrays;

public class LongestSubstringWithoutRepeatingCharacters {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int start = 0;
int end = 0;
int[] loc = new int[255];
Arrays.fill(loc, -1);
while (end < s.length()) {
int c = s.charAt(end);
start = loc[c] >= start ? loc[c] + 1 : start;
loc[c] = end;
max = Math.max(max, ++end - start);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode java 遍历