美文网首页
345. Reverse Vowels of a String

345. Reverse Vowels of a String

作者: 白菜炖豆腐 | 来源:发表于2016-05-15 00:13 被阅读0次

题目

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".

分析

题目意思是说,对一个字符串中的元音字母进行逆序,其他字母次序不变。
我的想法是,用i和j分别指向字符串中的每个字符,然后i从左往右搜索;j从右往左搜索;碰到是元音字母停止,然后将i和j位置的字符交换。当i>j的时候就代表已经完成了

代码

class Solution {
public:
    string reverseVowels(string s) {
        string result = s;
        int i=0;
        int j=s.size()-1;
        char temp;
        
        while(i<j){
            //从左往右搜索字母 
            while(i<s.length()){
                if(isVowels(result[i])){
                    break;
                }
                i++;
            } 
    
            //从右往左搜索字母
            while(j>-1){
                if(isVowels(result[j])){
                    break;
                } 
                j--;
            } 
    
            //交换字母
            if(i<j){
                temp = result[i];
                result[i] = result[j];
                result[j] = temp;
                i++;
                j--;
            }
        } 
         
        return result; 
    }
    
    //判断是否是元音字母 
    bool isVowels(char c){
        //将大写字母转为小写字母 
        if (c>='A'&&c<='Z'){
            c+=32; 
        } 
        //判断是否是元音字母 
        if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
            return true;
        }else{
            return false;
        }
    }
};

相关文章

网友评论

      本文标题:345. Reverse Vowels of a String

      本文链接:https://www.haomeiwen.com/subject/mglvrttx.html