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".
Note:
The vowels does not include the letter "y".
思路:
找到元音字母,標記位置,進行置換。
代碼如下:
// vowels(元音字母)包括:a,e,i,o,u. class Solution { public: bool isVowels(char c) { char vowels[10] = {'a','e','i','o','u','A','E','I','O','U'}; for(int i = 0; i < 10; i++) { if(c == vowels[i]) { return true; break;//return 和 break在一起都有反應么? } } return false; } string reverseVowels(string s) { vector<int> recordIndex; vector<char > str; for(int i = 0;i<s.size();i++) { str.push_back(s.at(i)); } for(int i = 0; i < str.size() ; i++) { if( isVowels(str[i]) ) { recordIndex.push_back(i); } } for(int i = 0 ; i < recordIndex.size() / 2 ; i++) { char left = str[recordIndex[i]]; char right = str[recordIndex[recordIndex.size() - 1 - i]]; str[recordIndex[i]] = right; str[recordIndex[recordIndex.size() - 1 - i]] = left; } s = ""; for(int i = 0 ; i < str.size() ; i++) { s.append(1,str[i]); } return s; } };
2016-08-08 10:52:10
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。