寻找最长连续子串
题目描述:给一个字符串str,找到str中最长的连续子串(不区分大小写),返回其长度。
例如:
input : str = adabc;
output : 3
思路:
1、连续:
利用ASCII值判断是否是连续字符,那么我们就认为它是连续字符,有now- pre = 1,那么now和pre是连续子串。
2、不区分大小写:
利用String类的toLowerCase()方法将str中的字符全转换为小写字符。
public class Main {
public static int seachMaxString(String str) {
if (str == null) return -1;
// 忽略大小写
str = str.toLowerCase();
// 找出最长连续子串
int max = 1; // 最大连续字符长度
int temp = 1; // 临时变量,记录当前连续的字符的长度
for(int i=1; i<str.length(); i++){
char pre = str.charAt(i-1);
char now = str.charAt(i);
if(now-pre==1){
temp++;
}else{
max=(max>temp?max:temp);
temp = 1;
}
}
max=(max>temp?max:temp); // 这里是为了防止输入字符串都是连续的,上述循环出来max为1不变
return max;
}
}