Given a string, find the length of the longest substring without repeating characters.java
- 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.
題目大意:給定一個字符串,找出不含有重複字符的最長子串的長度web
解讀Example面試
- 給定"abcabcbb",沒有重複字符的最長子串是"abc",那麼長度就是3
- 給定"bbbbb",最長子串就是"b",長度就是1
- 給定pwwkew,最長子串就是"wke",長度爲3,
- ==注意,==必須是一個子串."pwke",是子序列,而不是子串
到底如何在滑動窗口方法上優化了? 實際上咱們能夠若是採用進一步優化,能夠達到只須要N次便可計算成功.咱們能夠定義字符到索引映射.而不是使用集合來判斷這個字符的存在與否.當遇到重複的字符時,咱們便可跳過該滑動窗口.算法
也能夠理解爲,若是s[j]
在[i,j)
的範圍內有與j'重複的字符.咱們不須要逐漸增長i.而是直接跳過[i,j']
範圍內的全部元素.並將i
變成爲j'+1
就能夠作到.數組
java codebash
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;
}
}
複製代碼
字符串,其實由字符構成.而字符則能夠用ASC碼來替代.如此,咱們能夠用整數數組做爲直接訪問表來替換Map.學習
經常使用表以下:優化
int [26],用於表示字母 "a" - "z" 或 "A" - "Z";
ui
int [128],用於表示ASCII碼
spa
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;
}
}
複製代碼