LeetCode *** 345. Reverse Vowels of a String

来源:互联网 发布:提供rs485数据电缆价格 编辑:程序博客网 时间:2024/04/29 15:24

题目:

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


分析:


代码:

class Solution {public:string reverseVowels(string s) {int len = s.length();if (len < 2)return s;string t(len, ' ');int pre = 0, end = len - 1;while (pre < end) {while (pre < end&&!isVowel(s[pre])) {t[pre] = s[pre];pre++;}while (pre < end&&!isVowel(s[end])) {t[end] = s[end];end--;}if (pre < end&&isVowel(s[end]) && isVowel(s[pre])) {t[pre] = s[end];t[end] = s[pre];++pre;--end;}}if (pre == end)t[pre] = s[pre];return t;}bool isVowel(char c) {return tolower(c) == 'a' || tolower(c) == 'i' || tolower(c) == 'o' || tolower(c) == 'e' || tolower(c) == 'u' ;}};


0 0