一、题目再现
给定一个长度不超过10000的、仅由英文字母构成的字符串。请将字符重新调整顺序,按GPLTGPLT....
这样的顺序输出,并忽略其它字符。当然,四种字符(不区分大小写)的个数不一定是一样多的,若某种字符已经输出完,则余下的字符仍按GPLT
的顺序打印,直到所有字符都被输出。
输入格式:
输入在一行中给出一个长度不超过10000的、仅由英文字母构成的非空字符串。
输出格式:
在一行中按题目要求输出排序后的字符串。题目保证输出非空。
输入样例:
pcTclnGloRgLrtLhgljkLhGFauPewSKgt
输出样例:
GPLTGPLTGLTGLGLL
二、思路
- 从题中可以看出,我们应该用string容器,解题更方便一点,因为他里面内置了查找和删除(擦除)函数。
- 我自己写了一个函数,用来查找指定字符并输出。
- 因为它是不区分大小写的,所以我给func()指定了两个参数,用来接收大、小写字母。
- 我发现find()函数不能这样用int pos = str.find('d' || 'x'); 哈哈哈 ||是逻辑运算符,它的两边只能是bool类型的式子。 而且find也没有这种用法,只能接收一个字符或者字符串,然后进行比较 查找,并返回位置。
- 所以我就分开写的。int pos1 = str.find(d); int pos2 = str.find(x);
- 后来我想的是查找两个字符中的任意一个字符是否在输入的字符串中,并且返回查找到第一个元素的的位置。其实题中并没有要求这样。
- 题中的意思应该是只要你查到了,比如有G或者g(无论大小写),都输出一个大写,然后随意抹去一个字母即可(比如G或者g即可)
- 最后在main函数中调用该函数,用的是for循环
- 其实这里的循环还能优化一下,用str.length()的话,相当于字符串多少个字母就循环了多少次。但是下面写了4个func(),相当于删除了四个字符。这里可以优化一下,我有时间再看看。
- 其实这里的循环还能优化一下,用str.length()的话,相当于字符串多少个字母就循环了多少次。但是下面写了4个func(),相当于删除了四个字符。这里可以优化一下,我有时间再看看。
三、代码
下面这个是只要你查到了,比如有G或者g(无论大小写),都输出一个大写,然后随意抹去一个字母即可(比如G或者g即可)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string str;
void func(char &d, char &x);
int main() {
cin >> str;
char G = 'G';
char g = 'g';
char P = 'P';
char p = 'p';
char L = 'L';
char l = 'l';
char T = 'T';
char t = 't';
int maxlength = str.length();
for (int i = 0; i < maxlength; i++)
{
func(G, g);
func(P, p);
func(L, l);
func(T, t);
}
return 0;
}
//查找指定字符并输出
void func(char &d,char &x) { //d 为大写字母,x 为小写字母
/*int pos = str.find('d' || 'x');*/
int pos1 = str.find(d);
int pos2 = str.find(x);
int firstpos = -1;
//if (pos1 >= 0 && pos2 >= 0)
//{
// firstpos = std::min(pos1, pos2);//查找两个字符中的任意一个字符是否在输入的字符串中,并且返回查找到第一个元素的的位置
//}
//else if( (pos1 >= 0 && pos2 < 0) || (pos1 < 0 && pos2 >= 0) )//只要有一个字母,无论大小写,就返回那个位置
//{
// firstpos = std::max(pos1, pos2);
//}
if (pos1 != -1 || pos2 != -1)
{
firstpos = max(pos1, pos2);
}
if (firstpos >= 0)
{
cout << d;//题目要求输出的都大写
str.erase(firstpos, 1);
}
}
查找两个字符中的任意一个字符是否在输入的字符串中,并且返回查找到第一个元素的的位置。其实题中并没有要求这样。但是这样更符合常理更高级哈哈哈
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string str;
void func(char &d, char &x);
int main() {
cin >> str;
char G = 'G';
char g = 'g';
char P = 'P';
char p = 'p';
char L = 'L';
char l = 'l';
char T = 'T';
char t = 't';
int maxlength = str.length();
for (int i = 0; i < maxlength; i++)
{
func(G, g);
func(P, p);
func(L, l);
func(T, t);
}
return 0;
}
//查找指定字符并输出
void func(char &d,char &x) { //d 为大写字母,x 为小写字母
/*int pos = str.find('d' || 'x');*/
int pos1 = str.find(d);
int pos2 = str.find(x);
int firstpos = -1;
if (pos1 >= 0 && pos2 >= 0)
{
firstpos = std::min(pos1, pos2);//查找两个字符中的任意一个字符是否在输入的字符串中,并且返回查找到第一个元素的的位置
}
else if( (pos1 >= 0 && pos2 < 0) || (pos1 < 0 && pos2 >= 0) )//只要有一个字母,无论大小写,就返回那个位置
{
firstpos = std::max(pos1, pos2);
}
//if (pos1 != -1 || pos2 != -1)
//{
// firstpos = max(pos1, pos2);
//}
if (firstpos >= 0)
{
cout << d;//题目要求输出的都大写
str.erase(firstpos, 1);
}
}
上述两份代码都可以正确提交并运行!
欢迎大家在评论区交流碰撞!