用C语言实现【问题描述】 处理一个只含有0-9和a-z的字符串,使得输出字符串满足: 每个子片段中的字符都是严格升序排列的,按照ascii码顺序即可 下一个子片段必须与前一个子片段相同,或者是其子集 如果输入非法,应该输出 <invalid input string> 【输入形式】 一行字符串 【输出形式】 处理后的字符串 【样例输入】 aabbccdd 007799aabbccddeeff113355zz 1234.89898 abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee 【样例输出】 abcdabcd 013579abcdefz013579abcdefz <invalid input string> abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa
时间: 2024-02-17 10:01:01 浏览: 267
以下是使用C语言实现该问题的代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 1000
void sort(char *str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
void print_substring(char *start, char *end) {
for (char *p = start; p <= end; p++) {
printf("%c", *p);
}
}
int is_valid(char *str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (!isdigit(str[i]) && !islower(str[i])) {
return 0;
}
}
return 1;
}
int main() {
char str[MAX_LENGTH];
if (fgets(str, MAX_LENGTH, stdin) == NULL) {
return 0;
}
int len = strlen(str);
if (str[len - 1] == '\n') {
str[len - 1] = '\0';
}
if (!is_valid(str)) {
printf("<invalid input string>");
return 0;
}
int start = 0;
for (int i = 1; i <= len; i++) {
if (i == len || str[i] != str[start]) {
sort(str + start, str + i);
print_substring(str + start, str + i - 1);
start = i;
}
}
return 0;
}
```
代码的思路如下:
首先判断输入的字符串是否合法,即是否只包含数字和小写字母。如果不合法,则输出 `<invalid input string>`。
然后遍历字符串,将其分割成若干个子片段,并对每个子片段进行排序后输出。具体的分割方法如下:
- 从左到右遍历字符串,记录当前子片段的起始位置 start。
- 如果当前字符与前一个字符相同,则继续遍历;否则,将当前子片段排序后输出,并更新 start。
排序使用了简单的冒泡排序,时间复杂度为 O(n^2)。如果需要更高效的排序算法,可以使用快速排序等。
输出子片段时,使用了指针操作,避免了复制字符串的开销。
完整的代码见上。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)