java:输入一个字符串,在其中寻找长度最长的,不含重复字符的字符串,如果有多个长度相同的最长子字符串,则全部输出子字符串()-java
java:输入一个字符串,在其中寻找长度最长的,不含重复字符的字符串,如果有多个长度相同的最长子字符串,则全部输出子字符串()
public class test2 { public static List<String> findLongestSubstring(String s) { List<String> result = new ArrayList<>(); int n = s.length(); Map<Character, Integer> map = new HashMap<>(); int start = 0, end = 0, len = 0; while (end < n) { char c = s.charAt(end); if (map.containsKey(c)) { start = Math.max(start, map.get(c) + 1); } map.put(c, end); if (end - start + 1 > len) { len = end - start + 1; result.clear(); result.add(s.substring(start, end + 1)); } else if (end - start + 1 == len) { result.add(s.substring(start, end + 1)); } end++; } return result; } public static void main(String[] args) { String s = "abcabcbb"; List<String> result = findLongestSubstring(s); System.out.println(result); } }该代码的核心思想是使用哈希表存储每个字符最近一次出现的位置。遍历字符串时,如果遇到重复字符,更新起始位置为上一个该字符的位置加一。同时,记录下最长的子字符串长度和所有长度相同的子字符串。最后返回所有长度相同的子字符串。
上面的代码中,
主要的时间复杂度来自于遍历字符串和哈希表的操作。遍历字符串的时间复杂度为O(n),其中n是字符串的长度。每个字符在哈希表中的查找和更新都需要O(1)的时间。因此,总的时间复杂度为O(n)。
空间复杂度方面,哈希表最多存储不同字符的数量,因此空间复杂度为O(k),其中$k$是不同字符的数量。在本题中,由于只考虑ASCII码字符,因此$k$的最大值为$128$。因此,空间复杂度为O(1)。
综上所述,该算法的时间复杂度为O(n),空间复杂度为O(1)。这是一个非常高效的算法,可以在很短的时间内找到最长的不含重复字符的子字符串。
————————
public class test2 { public static List<String> findLongestSubstring(String s) { List<String> result = new ArrayList<>(); int n = s.length(); Map<Character, Integer> map = new HashMap<>(); int start = 0, end = 0, len = 0; while (end < n) { char c = s.charAt(end); if (map.containsKey(c)) { start = Math.max(start, map.get(c) + 1); } map.put(c, end); if (end - start + 1 > len) { len = end - start + 1; result.clear(); result.add(s.substring(start, end + 1)); } else if (end - start + 1 == len) { result.add(s.substring(start, end + 1)); } end++; } return result; } public static void main(String[] args) { String s = "abcabcbb"; List<String> result = findLongestSubstring(s); System.out.println(result); } }该代码的核心思想是使用哈希表存储每个字符最近一次出现的位置。遍历字符串时,如果遇到重复字符,更新起始位置为上一个该字符的位置加一。同时,记录下最长的子字符串长度和所有长度相同的子字符串。最后返回所有长度相同的子字符串。
上面的代码中,
主要的时间复杂度来自于遍历字符串和哈希表的操作。遍历字符串的时间复杂度为O(n),其中n是字符串的长度。每个字符在哈希表中的查找和更新都需要O(1)的时间。因此,总的时间复杂度为O(n)。
空间复杂度方面,哈希表最多存储不同字符的数量,因此空间复杂度为O(k),其中$k$是不同字符的数量。在本题中,由于只考虑ASCII码字符,因此$k$的最大值为$128$。因此,空间复杂度为O(1)。
综上所述,该算法的时间复杂度为O(n),空间复杂度为O(1)。这是一个非常高效的算法,可以在很短的时间内找到最长的不含重复字符的子字符串。