3. Longest Substring Without Repeating Characters
Posted gopanama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
自己方法复杂度比较高
可以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的主要内容,如果未能解决你的问题,请参考以下文章
longest-substring-with-at-least-k-repeating-characters
LeetCode 395. Longest Substring with At Least K Repeating Characters
395. Longest Substring with At Least K Repeating Characters
3. Longest Substring Without Repeating Characters
Leetcode: Longest Substring with At Least K Repeating Characters