九章算法面試高頻題沖刺班2021
最長不含重復(fù)字符的子字符串(劍指offer48題)
請從字符串中找出一個(gè)最長的不包含重復(fù)字符的子字符串,計(jì)算該最長子字符串的長度。
示例?1:
輸入: "abcabcbb"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長子串是 "abc",所以其長度為 3。
雙指針+哈希表 時(shí)間復(fù)雜度O(N) 空間復(fù)雜度O(1):字符的 ASCII 碼范圍為 0 ~ 127 , 哈希表 dicdic 最多使用 O(128) = O(1)大小的額外空間。class Solution { ? ?public int lengthOfLongestSubstring(String s) { ? ? ? ?Map<Character, Integer> dic = new HashMap<>(); ? ? ? ?int i = -1, res = 0; ? ? ? ?for(int j = 0; j < s.length(); j++) { ? ? ? ? ? ?if(dic.containsKey(s.charAt(j))) ? ? ? ? ? ? ? ?i = Math.max(i, dic.get(s.charAt(j))); // 更新左指針 i ? ? ? ? ? ?dic.put(s.charAt(j), j); // 哈希表記錄 ? ? ? ? ? ?res = Math.max(res, j - i); // 更新結(jié)果 ? ? ? ?} ? ? ? ?return res; ? ?} }
標(biāo)簽: