LeetCode3—Longest Substring Without Repeating Characters

刺骨的言语ヽ痛彻心扉 2022-06-09 07:38 219阅读 0赞

本类型博客中的各算法的时间复杂度分析均为博主自己推算,本类型博客也是博主自己刷LeetCode的自己的一些总结,因此个中错误可能较多,非常欢迎各位大神在博客下方评论,请不吝赐教

#

一、问题

  • 输入:一个字符串S
  • 输出:输出它的最长子串,该子串中不能包含相同的字符
  • 假设条件:字符串中的字符全部时ASCII吗,即编码值在0-128之间

二、输入输出示例

  • 输入:“abcaa”
  • 输出:3,因为最长子串为”abc”

三、解法

最大不重复子串肯定包含在两个重复的字符之间,或者是某个字符跟开头或结尾之间的子串为最大不重复子串。因此在遍历时凡是第一次遇到重复的字符,其之间的子串必定是不重复的,此时判断该子串的长度,并与已经存在的最大长度作比较,然后新的子串必定位于重复的两个字符的左侧那个字符的右边,然后在右边继续使用之前的方法寻找子串即可。对于字符串的遍历为n,另一个部分则是在已经遍历的字符中的搜索当前字符,整体算法的时间复杂度为n*搜索算法的时间复杂度。

解法一:使用散列思想存储已经遍历的字符

解题思路:由于本题中的字符均为ASCII字符,因此最多有128种字符,创建一个长度为128的数组,每个位置存储该字符最近一次出现的索引,这样查找的时间复杂度为O(1)

  1. package com.happy.leetcode.p3;
  2. public class LongestSubstringWithoutRepeatingCharactersV1 {
  3. public static void main(String[] args) {
  4. String s = "au";
  5. System.out.println(s);
  6. System.out.println(new LongestSubstringWithoutRepeatingCharactersV1().lengthOfLongestSubstring(s));
  7. }
  8. public int lengthOfLongestSubstring(String s) {
  9. if ("".equals(s.trim())) {
  10. return 0;
  11. }
  12. int[] characters = new int[128];
  13. int maxLength = 1;
  14. int currentLength = 0;
  15. int currentPos = -1;
  16. for (int i = 0; i < s.length(); i++) {
  17. int index = (int) s.charAt(i);
  18. if (characters[index] > 0 && characters[index]>currentPos) {
  19. currentLength = i - 1 - currentPos;
  20. currentPos = characters[index] - 1;
  21. if (maxLength < currentLength) {
  22. maxLength = currentLength;
  23. }
  24. }
  25. characters[index] = i + 1;
  26. }
  27. currentLength = s.length() - 1 - currentPos;
  28. if (maxLength < currentLength) {
  29. maxLength = currentLength;
  30. }
  31. return maxLength;
  32. }
  33. }

时间复杂度分析:n*1,时间复杂度为 O(n)

【注】该算法不是通用算法,由于散列算法的限制,因此该算法仅仅针对ASCII码字符

解法二:搜索采用Java的indexOf函数

解题思路:搜索时可以采用Java自带的indexOf函数,其实此函数实际为遍历一遍各个字符,找到想等的就返回索引

  1. package com.happy.leetcode.p3;
  2. public class LongestSubstringWithoutRepeatingCharactersV2 {
  3. public static void main(String[] args) {
  4. String s = "cddba";
  5. System.out.println(s);
  6. System.out.println(new LongestSubstringWithoutRepeatingCharactersV2().lengthOfLongestSubstring(s));
  7. }
  8. public int lengthOfLongestSubstring(String s) {
  9. if ("".equals(s.trim())) {
  10. return 0;
  11. }
  12. int maxLength = 1;
  13. int currentLength = 0;
  14. int currentPos = 0;
  15. for (int i = 0; i < s.length(); i++) {
  16. int index = s.indexOf(s.charAt(i), currentPos);
  17. if (index >= 0 && index < i) {
  18. currentLength = i - currentPos;
  19. currentPos = index + 1;
  20. if (maxLength < currentLength) {
  21. maxLength = currentLength;
  22. }
  23. }
  24. }
  25. currentLength = s.length() - currentPos;
  26. if (maxLength < currentLength) {
  27. maxLength = currentLength;
  28. }
  29. return maxLength;
  30. }
  31. }

时间复杂度分析:indexOf的时间复杂度为n,因此总的时间复杂度为 O(n^2)

#

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读