题目背景:用户输入n(n<=5)个单词,每个单词长度不超过30。反转元音字母,即将这几个单词从左往右数的第一个元音字母和从右往左数的第一个元音字母互换位置。
注:元音字母包括大小写
范例输入:
5
apple
opEpp
ioppp
pppIO
leetcode
范例输出:
eppla
Epopp
oippp
pppOI
leotcede
思路:利用双指针。将单词分为两半,分别考虑前半和后半部分的元音字母的情况,记录下元音字母及其位置,再分情况来交换。
示例代码: ——for the final version
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
//用户输入n个单词, n<=5, 每个单词长度不超30
char arr[5][30];
for (int i = 0; i < n; i++)
{
cin >> arr[i]; //cin后系统自动在末尾加一个\0
}
//统计每个单词的长度
int len[5] = { 0 };
for (int i = 0; i < n; i++)
{
for (int j = 0; arr[i][j] != '\0'; j++)
{
len[i]++;
}
}
for (int i = 0; i < n; i++)
{
//分别存元音字母在单词中的下标
int where1[15] = { 0 };
int where2[15] = { 0 };
//头尾指针,分别指向单词的第一个和最后一个字母
char* head = &arr[i][0];
char* tail = &arr[i][len[i] - 1];
//暂存元音字母
char temp1[15] = { 0 };
char temp2[15] = { 0 };
//t即半段中元音的个数
int t1 = 0, t2 = 0;
//让头尾指针不断往中间移动,count统计移动了几次
for (int count = 1; head <= tail; head++, tail--, count++)
{
if (*head == 'a' || *head == 'e' || *head == 'i' || *head == 'o' || *head == 'u' || *head == 'A' || *head == 'E' || *head == 'I' || *head == 'O' || *head == 'U')
{
temp1[t1] = *head;
where1[t1] = count;
t1++;
}
if (*tail == 'a' || *tail == 'e' || *tail == 'i' || *tail == 'o' || *tail == 'u' || *tail == 'A' || *tail == 'E' || *tail == 'I' || *tail == 'O' || *tail == 'U')
{
temp2[t2] = *tail;
where2[t2] = len[i] - count + 1;
t2++;
}
}
//当单词的后半部分没有元音字母时
if (t2 == 0)
{
for (int y = 0; t1 != 0; y++, t1--)
{
arr[i][where1[y] - 1] = temp1[t1 - 1];
arr[i][where1[t1 - 1] - 1] = temp1[y];
}
}
//当单词的前半部分没有元音字母时
if (t1 == 0)
{
for (int y = 0; t2 != 0; y++, t2--)
{
arr[i][where2[y] - 1] = temp2[t2 - 1];
arr[i][where2[t2 - 1] - 1] = temp2[y];
}
}
for (int y = 0; t1 != 0 && t2 != 0; y++, t1--, t2--)
{
arr[i][where1[y] - 1] = temp2[y];
arr[i][where2[y] - 1] = temp1[y];
}
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << endl;
}
return 0;
}
运行截图: