首页 > 代码库 > Leetcode-Longest Substring Without Repeating Characters
Leetcode-Longest Substring Without Repeating Characters
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:
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s.isEmpty()) return 0; 4 Set<Character> set = new HashSet<Character>(); 5 int head = 0, end = 1; 6 set.add(s.charAt(0)); 7 int maxLen = 1; 8 int curLen = 1; 9 while (end<s.length()){10 char cur = s.charAt(end);11 if (!set.contains(cur)){12 set.add(cur);13 curLen++;14 end++;15 } else {16 while (s.charAt(head)!=cur){17 set.remove(s.charAt(head));18 curLen--;19 head++;20 }21 head++;22 end++;23 }24 if (curLen>maxLen) maxLen=curLen;25 }26 27 28 return maxLen;29 }30 }
Leetcode-Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。