3. Longest Substring Without Repeating Characters
leetcode 3.给定一字符串,求出最长不重复子串长度。
第一种方法就是穷举,计算每种情况,很容易想到,思路上很清晰很简单在此就不附上代码了
这里摘引一些好的做法:
用HashSet(哈希表) 做一个sliding window(滑动窗口) (可参考相关链接)
java:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int Max_len = 0, i = 0, j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
Max_len = Math.max(Max_len, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return Max_len;
}
}
Java (using hashmap)
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [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;
}
}
Java(ASII 128)
前面的实现都没有关于字符串的字符集的假设。如果我们知道字符集相当小,我们可以用整数数组替换Map作为直接访问表。常用的table有:
int[26]
for Letters 'a' - 'z' or 'A' - 'Z'int[128]
for ASCIIint[256]
for Extended ASCII
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
int[] index = new int[128]; // current index of character
// try to extend the range [i, j]
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;
}
}
从本题中学到了什么?
了解到了hashset与hashmap,sliding window 在解题中的基础应用。
相关学习链接推荐如下:
http://www.cnblogs.com/skywang12345/p/3311252.html
https://www.cnblogs.com/mozi-song/p/9567163.html
流转星云