采用“滑窗”的方法解决此问题
代码实现
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) {
return 0;
}
if (s.length() == 1) {
return 1;
}
int maxLength = 0;
int index = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int tempIndex = index;
while (tempIndex < i && s.charAt(tempIndex) != c) {
tempIndex++;
}
if (tempIndex != i) {
maxLength = Math.max((i - index), maxLength);
index = tempIndex + 1;
}
if (i == s.length() - 1) {
maxLength = Math.max((i - index + 1), maxLength);
}
}
return maxLength;
}
}
运行结果
输入
"cdd"
输出
2
预期结果
2