345. Reverse Vowels of a String

題目

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;
        }
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容