您好,欢迎来到花图问答。
搜索
您的当前位置:首页LeetCode-345. Reverse Vowels of

LeetCode-345. Reverse Vowels of

来源:花图问答

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;
 } 

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务