Saturday, 8 January 2022

Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Approach:  The idea is to traverse the string from both ends while skipping the non-vowels characters from both ends.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
char* reverseVowels(char* s) {
    int low = 0, high = strlen(s) - 1;
    char c;
    while(low < high){
        //move forward to skip consonant
        while(low < strlen(s) && tolower(s[low]) != 'a' && tolower(s[low]) != 'e' && tolower(s[low]) != 'i' && tolower(s[low]) != 'o' && tolower(s[low]) != 'u'){
            low++;
        }
        //move backward to skip consonant
        while(low < high && tolower(s[high]) != 'a' && tolower(s[high]) != 'e' && tolower(s[high]) != 'i' && tolower(s[high]) != 'o' && tolower(s[high]) != 'u'){
            high--;
        }
        if(low < high){
           c = s[low];
           s[low] = s[high];
           s[high] = c;
           low++;
           high--;
        }
    }
    return s;
}
Share:

3 comments:

  1. Great explanation of reversing vowels in a string! It’s fascinating to see how concepts from flipperzerounleashed can inspire creative coding challenges!

    ReplyDelete
  2. "Your blog is a masterpiece! The way you articulate ideas is both enlightening and engaging. Thank you for sharing such valuable content—looking forward to your future posts!"

    ReplyDelete

Contact Me

Name

Email *

Message *

Popular Posts