hdu oj 2025

版权声明:本博客为博主原创文章,未经博主允许,禁止转载,谢谢合作。 https://blog.csdn.net/weixin_43971252/article/details/88363229

思路:
1.遍历字符串,找出最大的字符,记录最大字符
2.遍历字符串,找到最大字符的位置,并"(max)"插入到最大字符所在位置的下一个位置。
C++使用STL完成

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s;

	while (cin >> s) {
		char max_ch = 'A'; 

		//查找最大字符
		for (unsigned int i = 0; i < s.size(); i++) {
			if (s[i] > max_ch)
				max_ch = s[i];
		}

		//在最大字符后插入(max)
		for (unsigned int i = 0; i < s.size(); i++) {
			if (max_ch != 'x')
			{
				if (s[i] == max_ch) {
					if (i != s.size() - 1)
						s.insert(i + 1, "(max)");
					else
						s.append("(max)");
				}
			}
			else {                               //max_ch== 'x'是,指针步长加5,避免无限嵌套    
				if (s[i] == max_ch) {
					if (i != s.size() - 1)
						s.insert(i + 1, "(max)");
					else
						s.append("(max)");
					i += 5;
				}
			}
		}
		cout << s << endl;
	}
	
	return 0;
}

C语言使用字符串数组完成

#include<stdio.h>
#include<string.h>

void insert(char *str1, char* str2, int pos) {

	int len = strlen(str1);
	int insert_len = strlen(str2);

	//插入位置后的字符串后移:顺序从最后的字符开始
	for (int i = len - 1; i >= pos; i--)
		str1[i + insert_len] = str1[i];
	
	//插入字符串
	for (int i = 0; i < insert_len; i++)
		str1[i+pos] = str2[i];
	str1[len + insert_len] = 0;        //新的字符串末尾手动搞'0'作为结束
}

int main(void)
{
	/*
	//sizeof计算指针字符串大小按指针计算,strlen按字符串所含字符个数计算
	char *s = "sdhfsljhf";
	printf("%d , %d\n", sizeof(s), strlen(s));  //4 , 9
	char arr[] = "sdflhh";
	printf("%d , %d", sizeof(arr), strlen(arr));   //7,6
	*/

	char str[601];

	memset(str, 0, sizeof(str));
	while (scanf("%s%*c", str) != EOF)     //%*c 实现忽略最后一个输入字符,即回车
	{
		char max_ch = 'A';
		int len = strlen(str);
		for (int i = 0; i < len; i++)
			if (str[i] > max_ch)
				max_ch = str[i];

		int i = 0;
		while (i < len) {
			if (max_ch == str[i]) {
				insert(str, "(max)", i + 1);
				len += 5;
				i += 5;
			}
			else
				i++;
		}
		for (int i = 0; i < len; i++)
			putchar(str[i]);
		putchar('\n');
		memset(str, 0, sizeof(str));
	}
	
	return 0;
}


猜你喜欢

转载自blog.csdn.net/weixin_43971252/article/details/88363229