forked from wty21cn/leetcode-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq345-reverse-vowels-of-a-string.swift
71 lines (57 loc) · 2.08 KB
/
q345-reverse-vowels-of-a-string.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// q345-reverse-vowels-of-a-string.swift
// leetcode-swift
// Source* : https://leetcode.com/problems/reverse-vowels-of-a-string/
// Category* : String
//
// Created by Tianyu Wang on 16/7/2.
// Github : http://github.com/wty21cn
// Website : http://wty.im
// Linkedin : https://www.linkedin.com/in/wty21cn
// Mail : mailto:[email protected]
/***************************************************************************************
*
* 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".
*
***************************************************************************************/
import Foundation
struct q345 {
class Solution {
func reverseVowels(_ s: String) -> String {
if s.isEmpty {
return s
}
var s = s
let vowels = "aAeEiIoOuU".characters
var headIndex = s.startIndex
var tailIndex = s.characters.index(before: s.endIndex)
while headIndex < tailIndex{
while !vowels.contains(s[headIndex]) && headIndex < tailIndex {
headIndex = s.index(after: headIndex)
}
while !vowels.contains(s[tailIndex]) && headIndex < tailIndex {
tailIndex = s.index(before: tailIndex)
}
if headIndex == tailIndex {
break
}
let tmp = s[headIndex]
s.replaceSubrange(headIndex...headIndex, with: "\(s[tailIndex])")
s.replaceSubrange(tailIndex...tailIndex, with: "\(tmp)")
headIndex = s.index(after: headIndex)
tailIndex = s.index(before: tailIndex)
}
return s
}
}
static func getSolution() -> Void {
print(Solution().reverseVowels("12"))
}
}