版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)
题目来源:中国大学MOOC - 北京大学《数据结构与算法》- 第二章 线性表编程作业
1、字符串插入(10分)
题目内容:
有两个字符串str和substr,str和substr的字符个数不超过10^5,只包含大小写字母和数字。(字符个数不包括字符串结尾处的'\0'。)将substr插入到str中ASCII码最大的那个字符后面,若有多个最大则只考虑第一个。
输入格式:输入数据只有一行,格式为 str substr
输出格式:输出插入之后的字符串。
输入样例:abcab eee
输出样例:abceeeab
时间限制:500ms内存限制:32000kb
思路:因最大字符个数确定,所以可以采用顺序表进行存储和数据处理。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAX_LEN = 10000;
void solution();
int main()
{
int T = 0;
int t = 0;
T = 1;
while (t < T)
{
solution();
t++;
}
system("pause");
return 0;
}
void solution()
{
char str[MAX_LEN], substr[MAX_LEN];
int maxPos = 0;
int len1 = 0;
int len2 = 0;
cin >> str >> substr;
len1 = strlen(str);
len2 = strlen(substr);
//查找ASCII码最大字符所在位置
for (int i = 1; i < len1; i++)
{
if (str[i] > str[maxPos])
{
maxPos = i;
}
}
//该字符后所有字符后移len2位
for (int i = len1; i >= maxPos + 1; i--)
{
str[i + len2] = str[i];
}
//将substr插入至str之后
for (int i = 0; i < len2; i++)
{
str[i + maxPos + 1] = substr[i];
}
cout << str << endl;
}