给定“abcabcbb”,答案是“abc”,长度为 3。
给定“bbbbb”,答案是“b”,长度为 1。
给定“pwwkew”,答案是“wke”,长度为3。注意答案必须是子串,“pwke”是子序列而不是子串。
我想出了一个可行的解决方案,但在几个测试用例中都失败了。然后我找到了一个更好的解决方案,我重写了它以尝试理解它。下面的解决方案完美无缺,但经过大约 2 个小时的与这件事的斗争,我仍然不明白为什么这行特定的代码行得通。
import java.util.*;
import java.math.*;
public class Solution {
public int lengthOfLongestSubstring(String str) {
if(str.length() == 0)
return 0;
HashMap<Character,Integer> map = new HashMap<>();
int startingIndexOfLongestSubstring = 0;
int max = 0;
for(int i = 0; i < str.length(); i++){
char currentChar = str.charAt(i);
if(map.containsKey(currentChar))
startingIndexOfLongestSubstring = Math.max(startingIndexOfLongestSubstring, map.get(currentChar) + 1);
map.put(currentChar, i);
max = Math.max(max, i - startingIndexOfLongestSubstring + 1);
}//End of loop
return max;
}
}
有问题的行是
max = Math.max(max, i - startingIndexOfLongestSubstring + 1);
我不明白为什么会这样。我们取上一个最大值之间的最大值,以及我们当前索引和当前最长子字符串的起始索引之间的差异,然后加 1。我知道代码正在获取我们当前索引和startingIndexOfSubstring,但我无法概念化为什么它可以为我们提供预期的结果;有人可以向我解释这一步,特别是为什么它有效吗?