所有题目均有五种语言实现。C实现目录、C++ 实现目录、Python实现目录、Java实现目录、JavaScript实现目录
题目
请在一个字符串中找出连续最长的数字串,并返回这个数字串。
如果存在长度相同的连续数字串,返回最后一个。
如果没有符合条件的字符串,返回空字符串””。
注意
数字串可以由数字”0-9″、小数点”.”、正负号”±”组成,长度包括组成数字串的所有符号。
“.”、“±”仅能出现一次,”.”的两边必须是数字,”±”仅能出现在开头且其后必须要有数字。
长度不定,可能含有空格。
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
1234567890abcd9.+12345.678.9ed
输出
+12345.678
思路
1:此题的核心应该就在于+ - . 三个符号的判断。如果都是数字的话那就好办了。
2:代码逻辑
- 读取输入字符串:使用scanf读取字符串到char数组。
- 手动遍历字符串,识别符合模式的子串。
- 记录最长子串的位置和长度。
- 输出结果。
需要注意的细节:
- 正负号只能出现在数字的最前面。
- 小数点后必须有数字。
- 可能存在多个小数点的情况,但根据原代码的正则,应该是只允许一个小数点,后面跟数字。
考点
1:字符串处理
Code
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LEN 1024
int is_number_char(char c, int allow_sign, int allow_decimal) {
if (isdigit(c)) return 1;
if (allow_sign && (c == '+' || c == '-')) return 1;
if (allow_decimal && c == '.') return 1;
return 0;
}
void find_longest_number(const char *str, char *result) {
int max_len = 0;
int start_pos = 0;
int current_len = 0;
int decimal_point = 0;
int sign_allowed = 1;
for (int i = 0; str[i] != '\0';) {
if (is_number_char(str[i], sign_allowed, decimal_point == 0)) {
int valid = 1;
int temp_decimal = decimal_point;
int temp_sign = sign_allowed;
int j = i;
while (str[j] != '\0' && is_number_char(str[j], temp_sign, temp_decimal == 0)) {
if (str[j] == '+' || str[j] == '-') {
if (!temp_sign) {
valid = 0;
break;
}
temp_sign = 0;
} else if (str[j] == '.') {
if (temp_decimal) {
valid = 0;
break;
}
temp_decimal = 1;
temp_sign = 0;
} else {
temp_sign = 0;
}
j++;
}
if (valid && (j - i) >= max_len) {
max_len = j - i;
start_pos = i;
}
i = (valid && j > i) ? j : i + 1;
decimal_point = 0;
sign_allowed = 1;
} else {
i++;
decimal_point = 0;
sign_allowed = 1;
}
}
if (max_len > 0) {
strncpy(result, str + start_pos, max_len);
result[max_len] = '\0';
} else {
result[max_len] = '\0';
}
}
int main() {
char input[MAX_LEN];
char result[MAX_LEN] = {0};
if (fgets(input, MAX_LEN, stdin)) {
input[strcspn(input, "\n")] = '\0'; // 去除换行符
find_longest_number(input, result);
printf("%s\n", result ? result : "");
}
return 0;
}
要求
时间限制:C/C++ 1秒,其他语言 2秒
空间限制:C/C++262144K,其他语言524288K
64bit IO Format:%lld
语言限定:
C(clang11), C++(clang++11), Pascal(fpc 3.0.2), Java(javac 1.8), Python2(2.7.3),
PHP(7.4.7), C#(mcs5.4), ObjC(gcc 5.4), Pythen3(3.9), JavaScript Node(12.18.2), JavaScript V8(6.0.0),
Sqlite(3.7.9), R(4.0.3), Go(1.14.4), Ruby(2.7.1), Swift(5.3), matlab(Octave 5.2), Pypy2(pypy2.7.13),
Pypy3(pypy3.6.1), Rust(1.44), Scala(2.11.12), Kotlin(1.4.10), Groovy(3.0.6), TypeScript(4.1.2), Mysql(8.0)
更多题目链接:
华为OD 2025 最新最全机试题库及讲解,A+B+C+D+E卷题库大全。
Java题库: 2024华为OD机试(JAVA)真题【E卷+A卷+B卷+C卷+D卷】目录_华为od机试真题-CSDN博客
Python题库: 2024华为OD机试(Python)真题【E卷+A卷+B卷+C卷+D卷】目录_华为od机试好过吗-CSDN博客
C++题库: 2024华为OD机试(C++)真题【E卷+A卷+B卷+C卷+D卷】目录_华为od怎么知道考的是a卷还是b卷-CSDN博客
Js题库: 2024 华为OD机试(JavaScript)真题【E卷+A卷+B卷+C卷+D卷】目录_华为od 2023 q2b卷-CSDN博客