解题思路
这是一个字符串处理问题,需要找出字符串中最长的连续数字串。
关键点
-
输入规则:
- 字符串长度:
- 保证每组输入都至少含有一个数字
- 字符串长度:
-
输出要求:
- 输出最长的数字串及其长度
- 如果有多个相同长度的数字串,需要全部输出
- 按原字符串中的相对位置输出
实现思路
-
遍历处理:
- 遍历字符串,找到连续数字子串
- 记录每个数字串及其长度
- 找出最长长度
-
结果输出:
- 找出所有最长长度的数字串
- 按原顺序输出
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void findLongestDigits(string& str) {
vector<string> result;
int maxLen = 0;
string current;
// 遍历字符串
for (int i = 0; i <= str.length(); i++) {
if (i < str.length() && isdigit(str[i])) {
current += str[i];
} else if (!current.empty()) {
// 找到一个数字串
if (current.length() > maxLen) {
maxLen = current.length();
result.clear();
result.push_back(current);
} else if (current.length() == maxLen) {
result.push_back(current);
}
current.clear();
}
}
// 输出结果
for (int i = 0; i < result.size(); i++) {
cout << result[i];
}
cout << "," << maxLen << endl;
}
int main() {
string str;
while (getline(cin, str)) {
findLongestDigits(str);
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String str = sc.nextLine();
findLongestDigits(str);
}
}
public static void findLongestDigits(String str) {
List<String> result = new ArrayList<>();
int maxLen = 0;
StringBuilder current = new StringBuilder();
// 遍历字符串
for (int i = 0; i <= str.length(); i++) {
if (i < str.length() && Character.isDigit(str.charAt(i))) {
current.append(str.charAt(i));
} else if (current.length() > 0) {
// 找到一个数字串
if (current.length() > maxLen) {
maxLen = current.length();
result.clear();
result.add(current.toString());
} else if (current.length() == maxLen) {
result.add(current.toString());
}
current = new StringBuilder();
}
}
// 输出结果
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i));
}
System.out.println("," + maxLen);
}
}
def find_longest_digits(s):
result = []
max_len = 0
current = ''
# 遍历字符串
for i in range(len(s) + 1):
if i < len(s) and s[i].isdigit():
current += s[i]
elif current:
# 找到一个数字串
if len(current) > max_len:
max_len = len(current)
result = [current]
elif len(current) == max_len:
result.append(current)
current = ''
# 输出结果
print(''.join(result) + ',' + str(max_len))
while True:
try:
s = input()
find_longest_digits(s)
except:
break
算法及复杂度
算法分析
-
遍历过程:
- 逐字符遍历字符串
- 使用临时变量记录当前数字串
- 维护最大长度和结果列表
-
结果处理:
- 记录所有最长数字串
- 按原顺序保存和输出
复杂度分析
- 时间复杂度:
- 其中
是字符串长度,只需要遍历一次
- 空间复杂度:
- 需要存储找到的数字串