
问题
暴力方法将涉及创建给定字符串的所有可能的子字符串,并找出哪个是最长的没有重复字符的子字符串。这将导致 tc:o(n^2)
最佳方法:
tc:o(n)
sc : o(256),用于使用大小为 256 的 int[]
class Solution {
public int lengthOfLongestSubstring(String s) {
int hash[] = new int[256];// size of all the ascii characters
Arrays.fill(hash,-1); // -1 to indicate these indexes don't have any character visited already
int left =0,right =0;
int max = 0;
while(right<s.length()){
char c = s.charAt(right);
if(hash[c]!=-1){// means the character has been seen in the past
if(hash[c]>=left){// if the index of the character seen in the past is after the left pointer, then left pointer should be updated, to avoid duplicate in the window of substring
left = hash[c] + 1;// has to be 1 index after the index of last seen duplicate character
}
}
max = Integer.max(max, right-left+1);// keep track of mas window substring
hash[c] = right;// update the character last seen index in hash
right++;
}
return max;
}
}
以上就是没有重复字符的最长子串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号