2019獨角獸企業重金招聘Python工程師標準>>>
解題思路
首先要讀懂題目,它要求的是找到最長的子串,并且子串中沒有出現重復的字符。
我的想法,是用一個map存儲每個字符最后出現的位置,還要有個變量start,它用來記錄上一次出現重復的位置,如果當前字符上一次出現的位置比start小,那么說明中間出現了重復,不能當成有效的子串。記得就是在掃描結束后,再判斷一下最后一段子串。
給個圖簡單說明一下。
參考源碼
public class Solution {public int lengthOfLongestSubstring(String s) {if (s == null || s.isEmpty()) {return 0;}int max = 0;Map<Character, Integer> lastPos = new HashMap<Character, Integer>();int start = 0;lastPos.put(s.charAt(0), start);for (int i = 1; i < s.length(); i++) {char c = s.charAt(i);if (lastPos.containsKey(c) && lastPos.get(c) >= start) {if (i - start > max) {max = i - start;}start = lastPos.get(c) + 1;}lastPos.put(c, i);}if (s.length() - start > max) {max = s.length() - start;}return max;}
}