一、解題方法:滑動視窗
1.本題可以使用雙層for循環暴力破解,但是時間複雜度很高,會達到O(n^2),是以采用滑動視窗的方法來降低時間複雜度。
2.定義一個HashMap資料集合,其中key值為字元,value值為字元位置+1,+1表示從字元位置後一個開始不重複
3.我們定義不重複子串的開始位置為start,結束位置為end
4.随着end不斷周遊向後,會遇到與[start,end]區間内字元相同的情況,此時将字元作為key值,擷取其value值,并更新start,此時[start,end]區間内不存在重複字元
5.無論是否更新start,都會更新其map資料集合和結果ans
6.最終的時間複雜度是O(N)
二、代碼如下
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> hashMap = new HashMap<>();
int ans = 0;
for(int start = 0,end = 0;end < s.length();end++)
{
char ch = s.charAt(end);
if(hashMap.containsKey(ch))
{
start = Math.max(hashMap.get(ch),start);
}
ans = Math.max(ans,end-start+1);
hashMap.put(ch,end+1);
}
return ans;
}
}