3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
题目含义:获取最长子串,要去子串中没有重复字符
方法一:
dp[i]表示的是以i结尾的最长不含重复字符的子字符串。使用了hashmap这个数据结构记录<
char
,index>
如果map中没有当前这个元素,那么dp[i]=dp[i-
1
]+
1
如果map中存在当前的元素,一开始的想法是 dp[i]=i-map.get(array[i]),但是这样想有点问题,如果当前的字符串是abba的时候,按照刚才的思路dp[
0
]=
1
dp[
1
]=
2
dp[
2
]=
1
dp[
3
]=
3
但是dp[
3
]是错误的,因为中间存在了重复的字符。所以要加一种情况。
dp[i]=Math.min(dp[i-
1
]+
1
,i-map.get(array[i]))
public int lengthOfLongestSubstring(String s) { if (s == null) return 0; char[] array = s.toCharArray(); if (array.length == 1) { return 1; } int[] dp = new int[array.length]; int maxLength = Integer.MIN_VALUE; HashMap<Character, Integer> map = new HashMap<>(); dp[0] = 1; map.put(array[0], 0); for (int i = 1; i < array.length; i++) { dp[i] = 1; if (!map.containsKey(array[i])) { dp[i] = dp[i - 1] + 1; } else { dp[i] = Math.min(dp[i - 1] + 1, i - map.get(array[i])); } map.put(array[i], i); maxLength = Math.max(maxLength, dp[i]); } return maxLength; }
方法二:
1 public int lengthOfLongestSubstring(String s) { 2 if (s.length() == 0) return 0; 3 HashMap<Character,Integer> map = new HashMap<>(); //记录每个字符最后一次出现的位置 4 int max=0; 5 int j=0; 6 for (int i=0;i<s.length();i++) 7 { 8 char letter = s.charAt(i); 9 if (map.containsKey(letter)) 10 { 11 j = Math.max(j,map.get(letter)+1); //j表示上一个letter后面的字符位置 12 } 13 map.put(letter,i);//记录每个字符最后一次出现的位置 14 max = Math.max(max,i-j+1);//上一个letter后面的字符到i的长度,也就是非重复子串的长度 15 } 16 return max; 17 }