您的位置:首页 > 其它

LeetCode(3) - Longest Substring Without Repeating Characters

2017-03-12 13:56 477 查看
https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description

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

Examples:

Given 
"abcabcbb"
, the answer is 
"abc"
,
which the length is 3.

Given 
"bbbbb"
, the answer is 
"b"
,
with the length of 1.

Given 
"pwwkew"
, 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.

Solution:

整体思路是不断地记录唯一的char,当出现重复时,计算Length并清空记录。

由于用for来做,所以记得在最后的时候做最后的检测。

public int lengthOfLongestSubstring(String s) {
int maxLength = 0;

Set<Character> dict = new HashSet<>();
int start = 0;
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length; i++) {
if(!dict.add(chars[i])) {
int length = i - start;
if(length > maxLength) {
maxLength = length;
}

start = i;
dict.clear();
}
}

//last check
maxLength = maxLength > s.length() - start ? maxLength : s.length() - start;

return maxLength;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: