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;
}
}
复制代码