题目描述
在字符串中找出连续最长的数字串,并把这个串的长度返回;如果长度相同,返回最后一个连续字符串
样例输入
abcd12345ed125ss123456789
abcd12345ss54321
样例输出
输出123456789,函数返回值9
输出54321,函数返回值5
函数原型:
int Continumax(String intputStr, StringBuffer outputStr)
输入参数:
String intputStr 输入字符串
输出参数:
StringBuffer outputStr 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
返回值:
int 连续最长的数字串的长度
------解决方案--------------------
我改进了一下你在试试
public static int Continumax(String intputStr, StringBuffer outputStr) {
char[] charArray = intputStr.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < charArray.length; i++) {
if (Character.isDigit(charArray[i])) {
sb.append(charArray[i]);
} else {
sb.append(",");
}
}
String[] digitArray = sb.toString().replaceAll("(,)+", ",").split(",");//得到数字数组
if (digitArray.length <= 1) {
System.out.println("没有数字串!");
return 0;
}
List<String> digitList = new ArrayList<String>(Arrays.asList(digitArray));//转化为list方便操作
List<String> positiveDigitList = fetchContinueDigitByPositiveSort(digitList, true);//得到正向连续的数字比如1234,345
List<String> backDigitList = fetchContinueDigitByPositiveSort(digitList, false);//得到反向连续的数字比如4321,765
List<String> lastList = new ArrayList<String>();
lastList.addAll(positiveDigitList);
lastList.addAll(backDigitList);
int maxLength = 0;
String maxValue = "";
List<String> endStrList = new ArrayList<String>();
for (String s : lastList) { //找出最长并且是最后一个的值和长度