forked from keep-practicing/leetcode-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_vowels.go
77 lines (66 loc) · 1.15 KB
/
reverse_vowels.go
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
72
73
74
75
76
77
/*
345. Reverse Vowels of a String
https://leetcode.com/problems/reverse-vowels-of-a-string/
Write a function that takes a string as input and reverse only the vowels of a string.
*/
// time: 2018-12-26
package reversevowels
// time complexity: O(n)
// space complexity: O(1)
func reverseVowels(s string) string {
var (
l int
r = len(s) - 1
)
for r > l {
for r >= 0 && !isVowel(s[r]) {
r--
}
for l < len(s) && !isVowel(s[l]) {
l++
}
if l >= r {
break
}
charL := s[l]
charR := s[r]
s = s[:r] + string(charL) + s[r+1:]
s = s[:l] + string(charR) + s[l+1:]
r--
l++
}
return s
}
// time complexity: O(n)
// space complexity: O(n)
func reverseVowels1(s string) string {
bytes := []byte(s)
var (
l int
r = len(bytes) - 1
)
for r > l {
for r >= 0 && !isVowel(s[r]) {
r--
}
for l < len(bytes) && !isVowel(s[l]) {
l++
}
if l >= r {
break
}
bytes[l], bytes[r] = bytes[r], bytes[l]
l++
r--
}
return string(bytes)
}
func isVowel(char byte) bool {
vowels := [...]byte{'a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'}
for _, k := range vowels {
if char == k {
return true
}
}
return false
}