LeetCode3. Longest Substring Without Repeating Characters
程序员文章站
2022-03-21 19:46:18
...
思路:设定两个指针i,index,i负责遍历,index负责记录遍历过程中无重复字符的子串的开头,如果遍历过程中子串出现了重复字符,则将index指针指向重复字符的后一位,并计算长度,与最大值max进行比较,并更新重复字符的下标。
详细解答参考:https://www.cnblogs.com/StrayWolf/p/6701197.html?utm_source=itdadao&utm_medium=referral
代码:
public class LongestSubstringWithoutRepeatingCharacters3 {
public static void main(String[] args) {
String s = "abba";
System.out.println(lengthOfLongestSubstring(s));//输出2
}
public static int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0)
return 0;
int index = 0;
Map<Character, Integer> map = new HashMap<>();
int len = s.length();
int max = 0;
for (int i = 0; i < len; i++) {
if (map.containsKey(s.charAt(i))) {
index = Math.max(index, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - index + 1);
}
return max;
}
}
推荐阅读
-
Longest Substring Without Repeating Characters
-
LeetCode - 3.Longest Substring Without Repeating Characters(388ms)
-
[LeetCode]3.Longest Substring Without Repeating Characters
-
Leetcode_3. Find the longest substring without repeating characters
-
3-Longest Substring Without Repeating Characters @LeetCode
-
Longest Substring Without Repeating Characters (leetcode 3)
-
【Leetcode 3】Longest Substring Without Repeating Characters
-
Leetcode 3 Longest Substring Without Repeating Characters
-
leetcode【3】Longest Substring Without Repeating Characters
-
LeetCode(3)Longest Substring Without Repeating Characters