样例输入:
asdfetgfg 123df43 hg1234ds4321 a234dsf567sd657
样例输出:
null 123 1234 567
示例解题代码(Java):
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> strs = new ArrayList<String>();
//输入字符串
while(sc.hasNextLine()) {
String temp = sc.nextLine();
if(temp.equals(""))
break;
strs.add(temp);
}
//关闭Scanner
sc.close();
//运行查找函数
for(int i = 0; i < strs.size(); i++) {
System.out.println(getMaxSubStr(strs.get(i)));
}
}
public static String getMaxSubStr(String source) {
//抽取出source中的数字串
ArrayList<String> numbers = new ArrayList<String>();
int start = 0;
for(int i = 0; i < source.length(); i++) {
while(i < source.length() && !Character.isDigit(source.charAt(i))) {
i++;
}
start = i;
while(i < source.length() && Character.isDigit(source.charAt(i))) {
i++;
}
if(i - start > 1) {
numbers.add(source.substring(start, i));
}
}
//如果source中不含数字子串,则返回null
if(numbers.size() == 0) return null;
//找数字子串List中长度最大的串的下标maxIndex,比较时用小于号,这样找出的是第一个最长子串
int maxIndex = 0;
for(int i = 1; i < numbers.size(); i++) {
if(numbers.get(maxIndex).length() < numbers.get(i).length()) {
maxIndex = i;
}
}
//查找最长数字子串是否唯一,在maxIndexs中存放最长数字子串的下标
ArrayList<Integer> maxIndexs = new ArrayList<Integer>();
for(int i = 0; i < numbers.size(); i++) {
if(numbers.get(maxIndex).length() == numbers.get(i).length()) {
maxIndexs.add(i);
}
}
//如果最长数字子串不唯一(即maxIndexs长度大于1),则找出其中各字符对应数字之和最大的那个
if(maxIndexs.size() > 1) {
//计算每个最长子串各字符对应数字之和,存放在num数组中,num数组和maxIndexs一一对应
int[] num = new int[maxIndexs.size()];
for(int i = 0; i < maxIndexs.size(); i++) {
for(int j = 0; j < numbers.get(maxIndexs.get(i)).length(); j++) {
num[i] += "0123456789".indexOf(numbers.get(maxIndexs.get(i)).charAt(j));
}
}
//找出num中最大值的下标,通过maxIndexs找到这个下标所对应的numbers中的子串下标
int index = 0;
for(int i = 1; i < maxIndexs.size(); i++) {
if(num[index] < num[i])
index = i;
}
//maxIndex得到目标子串在numbers中的下标
maxIndex = maxIndexs.get(index);
}
//返回目标子串
return numbers.get(maxIndex);
}
}
getMaxSubStr()的计算流程:

原文:http://my.oschina.net/lovewxm/blog/517826