Topic description;
The role of each variable;
count: Record the number of characters that are different from the two identical characters (if any) in the substring being searched, the initial value is 0.
count1: Record the number of characters that are the same as those two identical characters in the substring, the initial value is -1.
PS: It was found in the subsequent submission that the substring can contain the same characters as those two identical characters.
flag: Record whether there are two identical characters.
max: The maximum string length found.
Code:
class Solution {
public int maxLengthBetweenEqualCharacters(String s) {
char[] ch = s.toCharArray();
int count = 0;
int count1 = -1;
int max = 0;
boolean flag = false;
for(int i = 0;i < ch.length;i++){
count = 0;
count1 = -1;
for(int j = i + 1;j < ch.length;j++){
if(ch[i] != ch[j]){
count++;
}else{
flag = true;
count1++;
if(count + count1 > max){
max = count + count1;
}
}
}
}
if(flag){
return max;
}
return -1;
}
}
result: