解题思路是遍历字符串,并将每一个字符存入hashmap中,以便判断是否已经存在。用一个计数器计数即可。/** * Created by Cookies on 2015-01-06. * 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 LengthOfLongestSubstring { public static void main(String[] args){ System.out.println(lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco")); } public static int lengthOfLongestSubstring(String s){ if (s==null) return 0; Map<Character,String> map = new HashMap<>(); int maxLength = 0; int count = 0; for (int i=0;i<s.length();i++){ if(map.containsKey(s.charAt(i))){ maxLength=Math.max(count,maxLength); count=1; map.clear(); map.put(s.charAt(i),""); }else{ ++count; maxLength=Math.max(count,maxLength); map.put(s.charAt(i),""); } } return maxLength; } }
LeetCode Longest Substring Without Repeating Characters 找到最长不重复字符串
最新推荐文章于 2024-09-05 10:48:32 发布