标签:com ash .com java color solution 复杂度 for Plan
自己方法复杂度比较高
可以O(n)的方法,遍历一遍 用两个指针记录maxstring的位置 然后遇到跟hashmap里重复的就更新指针
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1729/11-line-simple-Java-solution-O(n)-with-explanation
1 //Old 2 class Solution { 3 public int lengthOfLongestSubstring(String s) { 4 char[] arr = s.toCharArray(); 5 int max = 0; 6 for(int i = 0; i < arr.length; i++) { 7 max = Math.max(max, dfs(arr, new ArrayList<>(), i)); 8 } 9 return max; 10 11 } 12 13 public int dfs(char[] arr, List<Integer> list, int i) { 14 if(i >= arr.length || list.contains((int)arr[i])) return 0; 15 list.add((int)arr[i]); 16 return dfs(arr, list, i+1)+1; 17 } 18 19 } 20 21 22 23 24 //New 25 public int lengthOfLongestSubstring(String s) { 26 if (s.length()==0) return 0; 27 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 28 int max=0; 29 for (int i=0, j=0; i<s.length(); ++i){ 30 if (map.containsKey(s.charAt(i))){ 31 j = Math.max(j,map.get(s.charAt(i))+1); 32 } 33 map.put(s.charAt(i),i); 34 max = Math.max(max,i-j+1); 35 } 36 return max; 37 }
3. Longest Substring Without Repeating Characters
标签:com ash .com java color solution 复杂度 for Plan
原文地址:https://www.cnblogs.com/goPanama/p/9545865.html