In the answer, iota has already mentioned the root cause behind the problem. I am adding another way of finding the length of the longest substring.
- Using a nested loop, check all substrings, starting from a position till the end of the string, for the uniqueness of characters.
- Update the value of
max
(a variable to track the length of the longest substring) if a substring is found to be of greater length.
Demo:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(lengthOfLongestSubstring("qrsvbspk"));
}
public static int lengthOfLongestSubstring(String s) {
int max = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = s.length(); j >= i; j--) {
int len = j - i;
if (s.substring(i, j).chars().distinct().count() == len && len > max) {
max = len;
}
}
}
return max;
}
}
Output:
5
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…