請在一個字符串中找出連續最長的數字串,並返回這個數字串。
如果存在長度相同的連續數字串,返回最後一個。如果沒有符合條件的字符串,返回空字符串""。
注意:
數字串可以由數字"0-9"、小數點"."、正負號"±"組成,長度包括組成數字串的所有符號。"."、“±"僅能出現一次,”."的兩邊必須是數字,"±"僅能出現在開頭且其後必須要有數字。
長度不定,可能含有空格。
例子:1234567890abcd9.+12345.678.9ed
輸出:+12345.678
JAVA實現:
public static String function(String s) {
Pattern pattern = Pattern.compile("[+-]?[0-9]+(\\.[0-9]+)?");
Matcher matcher = pattern.matcher(s);
List<String> list = new ArrayList<>();
int i = 0;
while (matcher.find(i)) {
list.add(matcher.group());
i = matcher.start() + 1;
}
String result = "";
for (String target : list) {
if (target.length() >= result.length()) {
result = target;
}
}
return result;
}