LeetCode i48th 最长不含重复字符的子字符串
May 2020
1.题目
- 从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
2.解法
2.1 滑动窗口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| private static int longest(String str) { int length = str.length(); if (length == 0 || length == 1) return length; int left = 0; int longest = 0; for (int i = 1; i < length; ) { if (judge(str, left, i - 1, str.charAt(i))) { i++; longest = Math.max(longest, i - left); } else { left++; } } return longest; } private static boolean judge(String s, int left, int right, char c) { for (int i = left; i <= right; i++) { if (s.charAt(i) == c) return false; } return true; }
|
2.1HasHMap的滑动窗口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| private static int LM(String s) { if (s.length() == 0) { return 0; } int longest = 0; int head = 0; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) {
if (!map.containsKey(s.charAt(i))) { map.put(s.charAt(i), i); longest = Math.max(longest, i - head); } else { longest = Math.max(longest, i - head); if (map.get(s.charAt(i)) + 1 > head) { head = map.get(s.charAt(i)) + 1; } map.remove(s.charAt(i)); map.put(s.charAt(i), i); } } return Math.max(longest, s.length() - head); }
|
发布时间: 2020-05-01 17:56:10
更新时间: 2022-04-22 0:27:47
本文链接: https://wyatt.ink/posts/Airthmetic/e2dceda6.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!