文章目录
题目描述
给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度,字符串本身是其最长的子串,子串要求:
1、只包含 1 个字母(az,AZ),其余必须是数字:
2、字母可以在子串中的任意位置;
如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。
输入描述
字符串(只包含字母和数字)
输出描述
子串的长度
示例1
示例2
示例3
示例4
思路
滑动窗口
代码
public class Demo04 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()){
String string = in.nextLine();
//最大长度
int max = -1;
// 左侧指针
int l = 0;
// 字符数量
int letterCount = 0;
// r 右侧指针 左闭右闭
for (int r = 0; r < string.length(); r++) {
if (Character.isLetter(string.charAt(r))) {
letterCount++;
}
// 字符数量是1
if (letterCount == 1 && Character.isDigit(string.charAt(r))) {
max = Math.max(r-l+1, max);
continue;
}
// 字符数量超过1
if (letterCount == 2){
while (!Character.isLetter(string.charAt(l))){
l++;
}
l=l+1;
letterCount --;
max = Math.max(r-l+1==1?-1:r-l+1, max);
}
}
System.out.println(max);
}
}
}