最长无重复子串
最长无重复子串
思路:
同一个思路,两种方式实现
1. 使用HashMap
将字符串中的字符放入HashMap中,用字符作为HashMap的key,因此可以用该方式起到去重的方式。
2. 使用数组
相比哈希表,可以更节省资源。
1 import java.util.Arrays; 2 import java.util.HashMap; 3 4 /** 5 * @author: wooch 6 * @create: 2020/02/12 7 * 最长无重复子串 8 * 核心思路: 9 * 注意四个参数 10 * maxLength 最后结果 11 * preLength 当前字符的前一个字符的结果 12 * curLength 当前字符得到的结果 13 * dLength 重复字符的时候,该字符与上一个重复字符之间的长度 14 */ 15 public class LengthOfLongestSubstring { 16 public static void main(String[] args) { 17 System.out.println(lengthOfLongestSubstring("arbacacfr")); 18 System.out.println(lengthOfLongestSubstring("hkcpmprxxxqw")); 19 System.out.println(lengthOfLongestSubstring("dvdf")); 20 System.out.println(lengthOfLongestSubstring("tmmzuxt")); 21 System.out.println(lengthOfLongestSubstring("jbpnbwwd")); 22 23 System.out.println(maxLength("arabcacfr") == 4); 24 System.out.println(maxLength("a") == 1); 25 System.out.println(maxLength("aaa") == 1); 26 System.out.println(maxLength("abcdef") == 6); 27 System.out.println(maxLength("") == 0); 28 System.out.println(maxLength(null) == 0); 29 30 } 31 32 /** 33 * by hashMap 34 * 35 * @param str 36 * @return 37 */ 38 public static int lengthOfLongestSubstring(String str) { 39 if (str == null || str.length() == 0) { 40 return 0; 41 } 42 int len = str.length(); 43 char[] chs = str.toCharArray(); 44 HashMap<Character, Integer> map = new HashMap<>(); 45 int max = 0; 46 int count = 0; 47 for (int i = 0; i < len; i++) { 48 if (!map.containsKey(chs[i])) { 49 map.put(chs[i], i); 50 count++; 51 } else { 52 int index = map.get(chs[i]); 53 // 情况1:上次出现的该字符并不在当前所统计的最长字符串中,只需要更新位置信息。并且统计count++ 54 if (count < i - index) { 55 count++; 56 } else { 57 // 情况2:上次出现的该字符影响了当前最长不重复的子字符串 58 // 则更新位置信息、max变量和count计数 59 max = Math.max(max, count); 60 count = i - index; 61 } 62 map.put(chs[i], i); 63 } 64 } 65 // 防止出现没有重复字符的情况,此时max = 0 66 return Math.max(max, count); 67 } 68 69 /** 70 * by array 71 * 72 * @param str 73 * @return 74 */ 75 public static int maxLength(String str) { 76 if (str == null || str.length() <= 0) { 77 return 0; 78 } 79 int preLength = 0; //即f(i-1) 80 int curLength = 0; //即f(i) 81 int dLength = 0; //即与上一个同字符的距离 d 82 int maxLength = 0; 83 char[] chs = str.toCharArray(); 84 int len = chs.length; 85 int[] pos = new int[26]; //用于存放字母上次出现的位置 86 87 Arrays.fill(pos, -1); 88 89 for (int i = 0; i < len; i++) { 90 int letterNum = chs[i] - 'a'; 91 dLength = i - pos[letterNum]; 92 if (pos[letterNum] < 0 || dLength > preLength) { 93 curLength = preLength + 1; 94 } else { 95 curLength = dLength; 96 } 97 pos[letterNum] = i; 98 maxLength = Math.max(curLength, maxLength); 99 preLength = curLength; 100 } 101 102 return maxLength; 103 } 104 }

浙公网安备 33010602011771号