int n = s.size(); int i = 0, j = n - 1; while (i < j) { while (i < n && !isVowel(s[i])) { ++i; } while (j > 0 && !isVowel(s[j])) { --j; } if (i < j) { swap(s[i], s[j]); ++i; --j; } } return s; } };
publicclassSolution { publicstringReverseVowels(string s) { int n = s.Length; char[] arr = s.ToCharArray(); int i = 0, j = n - 1; while (i < j) { while (i < n && !IsVowel(arr[i])) { ++i; } while (j > 0 && !IsVowel(arr[j])) { --j; } if (i < j) { Swap(arr, i, j); ++i; --j; } } returnnewstring(arr); }
publicvoidSwap(char[] arr, int i, int j) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defreverseVowels(self, s: str) -> str: defisVowel(ch: str) -> bool: return ch in"aeiouAEIOU" n = len(s) s = list(s) i, j = 0, n - 1 while i < j: while i < n andnot isVowel(s[i]): i += 1 while j > 0andnot isVowel(s[j]): j -= 1 if i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 return"".join(s)
var reverseVowels = function(s) { const n = s.length; const arr = Array.from(s); let i = 0, j = n - 1; while (i < j) { while (i < n && !isVowel(arr[i])) { ++i; } while (j > 0 && !isVowel(s[j])) { --j; } if (i < j) { swap(arr, i, j); ++i; --j; } } return arr.join(''); }
funcreverseVowels(s string)string { t := []byte(s) n := len(t) i, j := 0, n-1 for i < j { for i < n && !strings.Contains("aeiouAEIOU", string(t[i])) { i++ } for j > 0 && !strings.Contains("aeiouAEIOU", string(t[j])) { j-- } if i < j { t[i], t[j] = t[j], t[i] i++ j-- } } returnstring(t) }
boolisVowel(char ch) { for (int i = 0; vowel[i]; i++) { if (vowel[i] == ch) { returntrue; } } returnfalse; };
char* reverseVowels(char* s) { int n = strlen(s); int i = 0, j = n - 1; while (i < j) { while (i < n && !isVowel(s[i])) { ++i; } while (j > 0 && !isVowel(s[j])) { --j; } if (i < j) { char* tmp = s[i]; s[i] = s[j], s[j] = tmp; ++i; --j; } } return s; }