【LeetCode】Longest Substring Without Repeating Characters

题目

Given a string, find the length of the longest substring without repeating characters.

Example 1:**

1
2
3
4
> Input: "abcabcbb"
> Output: 3
> Explanation: The answer is "abc", with the length of 3.
>

Example 2:

1
2
3
4
> Input: "bbbbb"
> Output: 1
> Explanation: The answer is "b", with the length of 1.
>

Example 3:

1
2
3
4
5
> Input: "pwwkew"
> Output: 3
> Explanation: The answer is "wke", with the length of 3.
> Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
>

思路

题目描述是给出一段英文字母字符串,求最长的且不含重复字母的子串。

记录最长子串的头、尾索引值,初始化为0、0

start = head 、end = tail + 1 双指针从前往后遍历,循环条件为 end < length

start == end ? end++;

判断end元素是否与start end之间的元素相同,

​ 相同则start = index(same) + 1 continue;

​ 不相同则判断 start - end > head - tail ? head = start , tail = end++ : end++;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class LeetCodeSolutionThird {

public static void main(String[] args) {
System.out.println("first:" + lengthOfLongestSubstring("abcabcbb"));
System.out.println("second:" + lengthOfLongestSubstring("bbbbb"));
System.out.println("third:" + lengthOfLongestSubstring("pwwkew"));
System.out.println("third:" + lengthOfLongestSubstring(""));
}

public static int lengthOfLongestSubstring(String s) {
char[] data = s.toCharArray();
int head = 0 , tail = 0;
if( data.length == 0 ) return data.length;
f:for( int start = head , end = tail + 1 ; end < data.length ;){
if( start == end ){
end++;
continue f;
}
s:for(int i = start ; i < end ; i++){
if( data[i] == data[end] ) {
start = i + 1;
continue f;
}
}
if( (end - start) > (tail - head)){
head = start;
tail = end;
}
end++;
}
return tail - head + 1;
}
}

Submission Detail

运行速度比98.98%提交者快,但内存消耗较大

提交结果分析


评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×