forked from gbrigens/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseVowelsOfAString.swift
37 lines (32 loc) · 1.05 KB
/
ReverseVowelsOfAString.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Question Link: https://leetcode.com/problems/reverse-vowels-of-a-string/
* Primary idea: Two pointers, iterate the string and swap two characters each time,
*
* Note: the input String is case sensitive; thus "aA" should be transferred to "Aa"
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class ReverseVowelsOfAString {
func reverseVowels(_ s: String) -> String {
var left = 0, right = s.count - 1
var chars = Array(s)
while left < right {
let isVowelLeft = isVowel(chars[left]), isVowelRight = isVowel(chars[right])
if isVowelLeft && isVowelRight {
chars.swapAt(left, right)
left += 1
right -= 1
} else {
if !isVowelLeft {
left += 1
} else {
right -= 1
}
}
}
return String(chars)
}
private func isVowel(_ char: Character) -> Bool {
return Set("aeiouAEIOU").contains(char)
}
}