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"
题意:反转字符串中元音字母的位置
方法1:用栈保存元音字符串,时间复杂度为O(2n)
static public string ReverseVowels(string s) {
Stack<char> vowelsStack = new Stack<char>();
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowelsStack.Push(c);
}
}
string rsult = "";
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
rsult += vowelsStack.Pop();
} else {
rsult += c;
}
}
return rsult;
}
方法2:使用两个指针,时间复杂度为O(n/2)
public class Solution {
public string ReverseVowels(string s) {
char[] cArr = s.ToArray();
int l = 0, r = s.Length - 1;
while (l < r) {
while (l < r && !IsVowels(cArr[l])) l++;
while (l < r && !IsVowels(cArr[r])) r--;
char temp = cArr[l];
cArr[l] = cArr[r];
cArr[r] = temp;
l++;
r--;
}
return new string(cArr);
}
public bool IsVowels(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
}
}