个人博客首页: KJ.JK
专栏介绍: 华为OD机试真题汇总,定期更新华为OD各个时间阶段的机试真题,每日定时更新,本专栏将使用C语言进行更新解答,包含真题,思路分析,代码参考,欢迎大家订阅学习
请在一个字符串中找出连续最长的数字串,并返回这个数字串。
如果存在长度相同的连续数字串,返回最后一个。
如果没有符合条件的字符串,返回空字符串””。
注意:
数字串可以由数字”0-9″、小数点”.”、正负号”±”组成,长度包括组成数字串的所有符号。
“.”、“±”仅能出现一次,”.”的两边必须是数字,”±”仅能出现在开头且其后必须要有数字。
长度不定,可能含有空格
输入
1234567890abcd9.+12345.678.9ed
输出
+12345.678
#include
#include
#include
char* findLongestNumberString(char* str) {
int length = strlen(str);
int start = -1, end = -1;
int maxLength = 0;
int currentStart = -1, currentEnd = -1;
int hasDot = 0;
int hasSign = 0;
for (int i = 0; i < length; i++) {
if (str[i] >= '0' && str[i] <= '9') {
if (currentStart == -1)
currentStart = i;
currentEnd = i;
} else if (str[i] == '+' || str[i] == '-') {
if (currentStart == -1 && !hasSign && (i + 1 < length) && (str[i + 1] >= '0' && str[i + 1] <= '9')) {
hasSign = 1;
currentStart = i;
currentEnd = i;
} else {
if (currentStart != -1) {
int currentLength = currentEnd - currentStart + 1;
if (currentLength >= maxLength) {
maxLength = currentLength;
start = currentStart;
end = currentEnd;
}
currentStart = -1;
currentEnd = -1;
}
hasDot = 0;
hasSign = 0;
}
} else if (str[i] == '.') {
if (currentStart != -1 && !hasDot && (i + 1 < length) && (str[i + 1] >= '0' && str[i + 1] <= '9')) {
hasDot = 1;
currentEnd = i + 1;
} else {
if (currentStart != -1) {
int currentLength = currentEnd - currentStart + 1;
if (currentLength >= maxLength) {
maxLength = currentLength;
start = currentStart;
end = currentEnd;
}
currentStart = -1;
currentEnd = -1;
}
hasDot = 0;
hasSign = 0;
}
} else {
if (currentStart != -1) {
int currentLength = currentEnd - currentStart + 1;
if (currentLength >= maxLength) {
maxLength = currentLength;
start = currentStart;
end = currentEnd;
}
currentStart = -1;
currentEnd = -1;
}
hasDot = 0;
hasSign = 0;
}
}
if (start != -1 && end != -1) {
int resultLength = end - start + 1;
char* result = malloc(sizeof(char) * (resultLength + 1));
strncpy(result, str + start, resultLength);
result[resultLength] = '\0';
return result;
} else {
return "";
}
}
int main() {
char str[] = "1234567890abcd9.+12345.678.9ed";
char* longestNumberString = findLongestNumberString(str);
printf(longestNumberString);
free(longestNumberString);
return 0;
}