LeetCode-345. Reverse Vowels of a String


Description

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

Note:
The vowels does not include the letter “y”.

题目分析
本题要求将所给字符串中的元音字母逆序排列,辅音字母不变,然后输出变换后的字符串。元音字母共5个(‘a’,’e’,’i’,’o’,’u’),其余均为辅音字母。
注意:本题所给字符串中包含大小写母,标点符号等。

解题思路

题目要求将字符串中的元音字母逆序排列,第一步,复制所给字符串,找到字符串中的元音字母并标记位置,然后将其按照在字符串中出现的顺序存储下来。第二步,按逆序将存储的元音字母依次填入新字符串标记的位置。第三步,返回新的字符串。

C语言代码

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


char* reverseVowels(char* strs) {
    int len=strlen(strs),i=0,j=0;
    char string1[len+1];             //非元音字符集 
    char string2[len+1];            //元音字符集 
    char *temp;
    temp=(char *)malloc(len+1);
    for (i=0;i<len;i++)
    {
        if(strs[i]=='a'||strs[i]=='e'||strs[i]=='i'||strs[i]=='o'||strs[i]=='u'
                ||strs[i]=='A'||strs[i]=='E'||strs[i]=='I'||strs[i]=='O'||strs[i]=='U')                //查找元音字母
            {
                string2[j]=strs[i];
                string1[i]=1;      //标记元音字母位置
                j++;
             }
        else 
            string1[i]=strs[i];
     } 

    string2[j]='\0';
    string1[i]='\0';
    i=0;
    while(string1[i]!='\0')
        {
            if(string1[i]==1)             //ascii为1的字符是通信控制字符,不会出现在字符串中,因而将其填入 
            {
                string1[i]=string2[j-1];        //逆序填入
                j--;
            }
            i++;
        }
    strcpy(temp,string1);
    return temp;
}


int main()
{
    char *strs="0:u`bVbu`:0";
    char *string;

   string=reverseVowels(strs);
    printf("%s",string);
    return 0;
 } 

参考文献
[1] https://leetcode.com/problems/reverse-vowels-of-a-string/#/description

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值