此题一开始以为是一个水题呢,以为只要一个index往后移动就行。但后来发现漏了一个大情况,"abcadef",最长应当是"bcadef"而不是“adef"。所以需要两个指针,begin和end。
1.对于这种两个指针,一个追着一个跑的,可以用一个while循环,end和start分别步进,当start赶上end时,再动end的写法;
2.只有当end步进时,才需要将c放入map;
3.看到网上很多人是用标志数组来存放上一次的index,会稍微省点空间和时间吧,但归根结底空间也是O(n)的,而且当字符时unicode的时候将不太好适用。(这个可以先确认题意。);
import java.util.HashMap; public class Solution { public int lengthOfLongestSubstring(String s) { // Start typing your Java solution below // DO NOT write main() function int max = 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int start = 0; char c = ' '; if (start < s.length()) { c = s.charAt(start); map.put(c, start); } int end = 0; while (end < s.length()) { c = s.charAt(end); // assume end >= start if (start == end) { map.put(c, end); end++; } else if (map.containsKey(c) && map.get(c) >= start)// duplicate char encountered { // update max if (end - start > max) max = end - start; start++; } else { map.put(c, end); end++; } } if (end - start > max) max = end - start; return max; } }
网上的一个代码,循环里有循环也挺好。
int lengthOfLongestSubstring(string s) { int n = s.length(); int i = 0, j = 0; int maxLen = 0; bool exist[256] = { false }; while (j < n) { if (exist[s[j]]) { maxLen = max(maxLen, j-i); while (s[i] != s[j]) { exist[s[i]] = false; i++; } i++; j++; } else { exist[s[j]] = true; j++; } } maxLen = max(maxLen, n-i); return maxLen; }