题目
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
解法
DP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) { return 0; } int len = s.length(); int[] dp = new int[len];
Map<Character, Integer> map = new HashMap<>(); dp[0] = 1; int res = dp[0]; map.put(s.charAt(0), 0); for (int i=1; i<len; i++) {
if (map.containsKey(s.charAt(i))) { int d = i - map.get(s.charAt(i)); if (d <= dp[i-1]) { dp[i] = d; } else { dp[i] = dp[i-1] + 1; } map.put(s.charAt(i), i); } else { map.put(s.charAt(i), i); dp[i] = dp[i-1]+1; } res = Math.max(res, dp[i]); } return res; }
|
滑动窗口
以i和j作为左右边界
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| private int test(String s) { Map<Character, Integer> map = new HashMap<>(); int i=-1, res=0; for (int j=0; j<s.length(); j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(i, map.get(s.charAt(j))); } map.put(s.charAt(j), j); res = Math.max(res, j-i); } return res; }
class Solution { public int lengthOfLongestSubstring(String s) { Set<Character> occ = new HashSet<Character>(); int n = s.length(); int rk = -1, ans = 0; for (int i = 0; i < n; ++i) { if (i != 0) { occ.remove(s.charAt(i - 1)); } while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) { occ.add(s.charAt(rk + 1)); ++rk; } ans = Math.max(ans, rk - i + 1); } return ans; } }
作者:LeetCode-Solution 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|