参考链接
这里只需要注意一下from的跳转即可,每次跳转的序号为to指向的字符在子串中出现的位置 + 1。
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
int from = 0;
int to = 0;
int length = 1;
int maxLength = 1;
while (to < s.length()) {
int site = s.substring(from, to).indexOf(s.charAt(to));
if (site != -1) {
length = to - from;
if (length > maxLength) maxLength = length;
from = from + site + 1;
}
to ++;
}
if (to - from > maxLength) {
maxLength = to - from;
}
return maxLength;
}
}
public class LengthOfLongestSubstring {
public static int lengthOfLongestSubstring(String s) {
/**
* left、right用于最后打印子串是什么,如果只是求最大无重复子串的长度,则可以不用这两个变量
*/
int left = 0; int right = 0;
if (s == null || s.length() == 0) return 0;
int from = 0;
int to = 1;
int length = 1;
int maxLength = 1;
/**
* to 遍历直到末尾
*/
while (to < s.length()) {
int site = s.substring(from, to).indexOf(s.charAt(to));
if (site != -1) {
length = to - from;
if (length > maxLength) {
maxLength = length;
/**
* 保留最大子串的左右下标,用于最后取出最大无重复子串,若只求子串最大长度,则这个逻辑可以不要
*/
left = from;
right = to;
}
from = from + site + 1;
}
to ++;
}
/**
* 处理最后子串
*/
if (to - from > maxLength) maxLength = to - from;
System.out.println(s.substring(left, right));
return maxLength;
}
public static void main(String arr[]) {
String s = "abccd";
int maxLength = lengthOfLongestSubstring(s);
System.out.println(maxLength);
}
}