题目:
题目链接:
https://leetcode.cn/problems/longest-substring-without-repeating-characters/
题目内容:
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
题解:语言java
方法1:
没有使用其他数据结构,使用字符串最low的拼接、截取和迭代,耗时和内存占用都很大
代码:
public int lengthOfLongestSubstring(String strFath) {
String curr = strFath;
String temp = "";
String result = "";
int i = 0;
while (i<curr.length()){
if (temp.indexOf(curr.charAt(i))>-1){
if (result.length()<temp.length()){
result = temp;
}
temp = "";
curr = curr.substring(curr.indexOf(curr.charAt(i))+1,curr.length());
i = 0;
continue;
}
temp = temp + curr.charAt(i);
i++;
}
return result.length()>temp.length()?result.length():temp.length();
}
方法2:
方法1改进:只记录了索引,减少大量的字符串裁剪,执行时间300多毫秒
代码:
public int lengthOfLongestSubstring(String strFath) {
String curr = strFath;
String temp = "";
String result = "";
int startIndex = 0;
int exitIndex = 0;
int i = 0;
while (i<curr.length()){
exitIndex = temp.indexOf(curr.charAt(i));
if (exitIndex >-1){
if (result.length()<temp.length()){
result = temp;
}
startIndex = startIndex + exitIndex + 1;
i = startIndex;
temp = "";
continue;
}
temp = temp + curr.charAt(i);
i++;
}
return result.length()>temp.length()?result.length():temp.length();
}
方法3:
引入LinkedList记录已经出现过的字符,利用它可以removeFirst()的优点,减少循环次数提升性能,时间和内存占用提升明显,执行时间20毫秒
public int lengthOfLongestSubstring(String strFath) {
String curr = strFath;
int resu = 0;
LinkedList<Character> occ = new LinkedList<Character>();
int n = curr.length();
char currChar = ' ';
for (int i = 0;i<n;i++){
currChar = curr.charAt(i);
if (!occ.contains(currChar)){
occ.add(currChar);
}
else {
resu = Math.max(resu,occ.size());
while (occ.contains(currChar)){
occ.removeFirst();
}
occ.add(currChar);
}
}
resu = Math.max(resu,occ.size());
return resu;
}
方法4:
使用官方给出的解题思路(移动窗口思想),时间直接减少到5ms
public int lengthOfLongestSubstring(String strFath) {
Set<Character> resuSet = new HashSet<Character>();
int ans = 0;
int k = -1;
int n = strFath.length();
for (int i = 0;i<n;i++){
if (i>0){
resuSet.remove(strFath.charAt(i-1));
}
while (k+1<n && !resuSet.contains(strFath.charAt(k+1))){
resuSet.add(strFath.charAt(k+1));
k = k+1;
}
ans = Math.max(ans,k+1-i);
}
return ans;
}
感悟:官方的解法还是经典