一.算法題
- 題目
Given a string, find the length of the longest substring without repeating characters.
- Example
- 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
- Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
二.算法題解讀
- 題目大意:給定一個字符串,找出不含有重復字符的最長子串的長度
- 解讀Example
- 給定"abcabcbb",沒有重復字符的最長子串是"abc",那么長度就是3
- 給定"bbbbb",最長子串就是"b",長度就是1
- 給定pwwkew,最長子串就是"wke",長度為3,
- ==注意,==必須是一個子串."pwke",是子序列,而不是子串
三.優化"滑動窗口"解決思路
到底如何在滑動窗口方法上優化了? 實際上我們可以如果采用進一步優化,可以達到只需要N次即可計算成功.我們可以定義字符到索引映射.而不是使用集合來判斷這個字符的存在與否.當遇到重復的字符時,我們即可跳過該滑動窗口.
也可以理解為,如果s[j]在[i,j)的范圍內有與j'重復的字符.我們不需要逐漸增加i.而是直接跳過[i,j']范圍內的所有元素.并將i變成為j'+1就可以做到.
四.代碼實現java code
public class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length(), ans = 0;//獲取當前字符索引Map<Character, Integer> map = new HashMap<>(); //修改[i,j]的范圍 for (int j = 0, i = 0; j < n; j++) {if (map.containsKey(s.charAt(j))) {i = Math.max(map.get(s.charAt(j)), i);}ans = Math.max(ans, j - i + 1);map.put(s.charAt(j), j + 1);}return ans;}
}
五.使用ASCII 128碼 思路
字符串,其實由字符構成.而字符則可以用ASC碼來替代.如此,我們可以用整數數組作為直接訪問表來替換Map.常用表如下:
int [26],用于表示字母 "a" - "z" 或 "A" - "Z";
int [128],用于表示ASCII碼
int [256],用于表示擴展ASCII碼
A = 65, a = 97

六.代碼實現java code
public class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length(), ans = 0;int[] index = new int[128]; for (int j = 0, i = 0; j < n; j++) {i = Math.max(index[s.charAt(j)], i);ans = Math.max(ans, j - i + 1);index[s.charAt(j)] = j + 1;}return ans;}
}
作為一個開發者,有一個學習的氛圍跟一個交流圈子特別重要,這是一個我的iOS交流群:642363427不管你是小白還是大牛歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 大家一起交流學習成長!