4ms solution in C with comments


  • 0
    S
    int isvowel(char c) {
        return
        c == 'a' || c == 'A' ||
        c == 'e' || c == 'E' ||
        c == 'i' || c == 'I' ||
        c == 'o' || c == 'O' ||
        c == 'u' || c == 'U';
    }
    
    void charswp(char* a, char* b) {
        char tmp = *a;
        *a = *b;
        *b = tmp;
    }
    
    char* reverseVowels(char* s) {
        int len = strlen(s);
        int itfwd = 0;              // forward iterator
        int itbwd = len - 1;        // backward iterator
        
        // continue until iterators overlap
        while (itfwd < itbwd) {
            // if chars at current iterator locations are vowels, swap chars and move iterators
            if (isvowel(s[itfwd]) && isvowel(s[itbwd])) {
                charswp(&s[itfwd], &s[itbwd]);
                ++itfwd;
                --itbwd;
            }
            
            // move both iterators until a vowel is found or iterators are out of bounds
            while (!isvowel(s[itfwd]) && itfwd <= len - 1)  ++itfwd;
            while (!isvowel(s[itbwd]) && itbwd >= 0)        --itbwd;
        }
        return s;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.