LeetCode Reverse Vowels of a String

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


把字符串中的所有元音字母逆序。简单题,使用首尾两个指针i,j,找到元音后交换,直到i>j。

完整代码如下:

class Solution {
public:
	string reverseVowels(string s) {
		unordered_set<char> vowels = { 'a','e','i','o','u','A','E','I','O','U' };
		int i = 0, j = s.size() - 1;
		while (i < j) {
			while (i < j&&vowels.find(s[i]) == vowels.end())++i;
			if (i >= j)break;
			while (i < j&&vowels.find(s[j]) == vowels.end())--j;
			if (i >= j)break;
			swap(s[i++], s[j--]);
		}
		return s;
	}
};

本代码提交AC,用时52MS。

Leave a Reply

Your email address will not be published. Required fields are marked *