题目描述
给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度,字符串本身是其最长的子串,子串要求:
1、 只包含1个字母(a~z, A~Z),其余必须是数字;
2、 字母可以在子串中的任意位置;
如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。
输入描述
字符串(只包含字母和数字)
输出描述
子串的长度
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int maxLen = -1;
boolean hasLetter = false;
int left = 0;
int right = 0;
LinkedList<Integer> indexList = new LinkedList<>();
while(right < str.length()){
char c = str.charAt(right);
if(isLetter(c)){
hasLetter = true;
indexList.add(right);
}
if(indexList.size()>1){
left = indexList.removeFirst() + 1;
}
if(left == right){
right++;
continue;
}
maxLen = Math.max(maxLen, right-left+1);
right++;
}
if(!hasLetter){
System.out.println(-1);
return;
}
System.out.println(maxLen);
}
public static boolean isLetter(char c){
return ((c<='z' && c>= 'a') || (c<='Z' && c>='A'));
}
}