首页 > 代码库 > Longest Substring Without Repeating Characters
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.
public class Solution { public static int lengthOfLongestSubstring(String s) { int count=0; int start=0; int max=0; Map<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++){ if(map.containsKey(s.charAt(i))!=true){ count++; map.put(s.charAt(i),i); } else{ if(max<count) max=count; if(start<map.get(s.charAt(i))) start=map.get(s.charAt(i)); count=i-start; map.put(s.charAt(i), i); } } if(max<count) max=count; return max; } }思路:O(n)解法,遍历字符串,逐个添加,用HashMap检查是否有重复字符,更新长度和统计的起始坐标。
下面这个写法代码更简洁一点。
public class Solution { public static int lengthOfLongestSubstring(String s) { int start=0; int max=0; Map<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++){ if(map.containsKey(s.charAt(i))==true){ if(start<=map.get(s.charAt(i))) start=map.get(s.charAt(i))+1;//update start index } map.put(s.charAt(i), i); if(max<(i-start+1)) max=i-start+1;//update max } return max; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。