题目:在字符串中找出连续最长的数字串,并把这个串的长度返回;如果长度相同,返回最后一个连续字符串
样例输入
abcd12345ed125ss123456789
abcd12345ss54321
样例输出
输出123456789,函数返回值9
输出54321,函数返回值5
函数原型:
int Continumax(String intputStr, StringBuffer outputStr)
输入参数:
String intputStr 输入字符串
输出参数:
StringBuffer outputStr 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串
返回值:
int 连续最长的数字串的长度
实现代码:
func findLongestNum(str:Array<String>){
var maxLengthNum:Int = 0 //定义最长数字字符串的长度
var maxLengthNumStr:Array<String> = [] //用来保持最长字符串
var nowLengthNum:Int = 0 //用于储存当前连续数字字符的字符串长度
var nowLengthNumStr:Array<String> = [] // 用于储存当前连续的数字字符串
for (var i = 0 ; i < str.count ; i++){
if (str[i] < "9" || str[i] > "0"){ //当前的字符串为数字时
nowLengthNum++ //当前连续数字字符串长度
nowLengthNumStr.append(str[i]) // 把当前连续的数字字符串赋予临时的字符串数组中
if(nowLengthNum > maxLengthNum){ // 当当前的字符串长度大于最大字符串长度时,把当前的字符串长度以及字符串赋予最大连续数字字符串和长度
maxLengthNum = nowLengthNum
maxLengthNumStr = nowLengthNumStr
}
}
if (str[i] > "9" || str[i] < "0"){ //一旦出现非数字字符串,立即重置临时当前的连续字符串与连续字符串长度
nowLengthNum = 0
nowLengthNumStr = []
}
}
println(maxLengthNum)
println(maxLengthNumStr)
}
//验证
var str2 = ["a","b","c","d","1","2","3","4","5","s","s","2","3","4","4","5","3","4","5","3","4"]
findLongestNum(str2)
//************************************输出结果*****************************************//
"10"
["2","3","4","4","5","3","4","5","3","4"]