YMLiang

* 给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
*
* 示例 1:
* 输入: "abcabcbb"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
* <p>
* 示例 2:
* <p>
* 输入: "bbbbb"
* 输出: 1
* 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
* <p>
* 示例 3:
* <p>
* 输入: "pwwkew"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
* 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
*/
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
public class LongestSubstring {
public static int lengthOfLongestSubstring(String s) {
int length = s.length();
if(length<2) {return length;}
Set set = new HashSet();
int res = 0;
int start = 0;
int end = 0;
while (end<length){
if(!set.contains(s.charAt(end))){
set.add(s.charAt(end++));
res = Math.max(res,set.size());
}else{
set.remove(s.charAt(start++));
}
}

return res;
}

public static void main(String[] args) {
int result = lengthOfLongestSubstring("abcabcbb");
System.out.println(result);
}
}

 评论


博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 Material X 作为主题 , 总访问量为 次 。
Copyright 2018-2019 YMLiang'BLOG   |   京ICP备 - 19039949  |  载入天数...载入时分秒...