这里的想法就是当从一个字符开始数,如若遇见第二个相同字符(含自己),那么这个子串的长度就到此为止了。例如 abcdb 从a开始,当其遇见第二个b时,这个子串已经到最长。
JAVA
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> posMap = new HashMap();
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
char key = s.charAt(i);
if (posMap.containsKey(key)) {
int keyPos = posMap.get(key);
List<Character> needRemove = new ArrayList<>();
for (Map.Entry<Character, Integer> characterIntegerEntry : posMap.entrySet()) {
int lastPos = characterIntegerEntry.getValue();
if (lastPos <= keyPos) {
if (maxLen < i - lastPos) {
maxLen = i - lastPos;
}
needRemove.add(characterIntegerEntry.getKey());
}
}
for (Character character : needRemove) {
posMap.remove(character);
}
}
posMap.put(key, i);
}
for (Integer value : posMap.values()) {
int len = s.length() - value;
if (len > maxLen) {
maxLen = len;
}
}
return maxLen;
}
}