class Solution {
public int getIndex(char target, char[] c_s, int start, int end) { // 包含 start 和 end
for (int i = end; i >= start; i--) {
if (c_s[i] == target) {
return i;
}
}
return -1;
}
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] c_s = s.toCharArray();
int len = c_s.length;
int[] dp = new int[len];
dp[0] = 1;
int max = 1;
for (int i = 1; i < len; i++) {
int index = getIndex(c_s[i], c_s, i - dp[i - 1], i - 1);
if (index == -1) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = i - index;
}
if (dp[i] > max) {
max = dp[i];
}
}
return max;
}
}
利用HashMap 来存储:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int temp = 0, max = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
int index = map.getOrDefault(s.charAt(i), -1);
map.put(s.charAt(i), i);
temp = temp < i - index ? temp + 1 : i - index;
max = Math.max(max, temp);
}
return max;
}
}