forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_vowels.cpp
66 lines (57 loc) · 1.19 KB
/
reverse_vowels.cpp
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
/*
* 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".
*
* Note:
* The vowels does not include the letter "y".
*/
#include <iostream>
#include <algorithm>
bool isVowel(char c)
{
return (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u' || c == 'A' ||
c == 'E' || c == 'I' ||
c == 'O' || c == 'U');
}
std::string reverseVowels(std::string s)
{
if (s.length() == 0)
{
return s;
}
unsigned int i = 0;
unsigned int j = s.length() - 1;
while (i < j)
{
while (i < j && !isVowel(s[i]))
{
i++;
}
while (i < j && !isVowel(s[j]))
{
j--;
}
if (i < j)
{
std::swap(s[i], s[j]);
++i;
--j;
}
}
return s;
}
int main()
{
std::string str;
std::cout << "Please enter input string: ";
std::cin >> str;
std::cout << "Expected output string: " << reverseVowels(str) << std::endl;
return 0;
}