Leetcode 345. Reverse Vowels of a String
345. Reverse Vowels of a String
- Total Accepted: 30572
- Total Submissions: 84744
- Difficulty: Easy
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".
思路:只交换元音字母。元音字母有a,e,i,o,u,不要忘了A,E,I,O,U。
代码:
1 class Solution { 2 public: 3 string reverseVowels(string s) { 4 string str="aeiouAEIOU"; 5 int i=0,j=s.size()-1; 6 while(i<j){ 7 i=s.find_first_of(str,i);//从第i个字符开始查找,返回str中第一个在s中出现的字符在s中的位置 8 j=s.find_last_of(str,j); 9 if(i<j){ 10 swap(s[i++],s[j--]); 11 } 12 } 13 return s; 14 } 15 };