My solution to this problem: the longest length will not exceed the number of non-repetitive characters n, so start with this number and find the substring length n. If n is not found, then n-=1 and search again.
Need to determine whether the substring is a non-repeating character.
class Solution {
public int lengthOfLongestSubstring(String s) {
int size = getSize(s);
System.out.println();
for (int i = 0; i < size; i++) {
int maxLength = size - i;//最大长度
for (int j = 0; j < s.length(); j++) {
String substring=null;
if (j + maxLength - 1 < s.length()) {
substring = s.substring(j, j+maxLength);
}
if (getSize(substring) == maxLength) {
return maxLength;
}
}
}
return 0;
}
private int getSize(String s) {
if (s==null){
return 0;
}
char[] chars = s.toCharArray();
// 得到无重复字符数
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < chars.length; i++) {
hashSet.add(chars[i]);
}
int size = hashSet.size();
return size;
}
}
To be optimized later