Why is my "reverse vowel" solution giving TLE message?


  • 0
    A
    static char VOWELS[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    static int NUM_VOWELS = sizeof(VOWELS) / sizeof(VOWELS[0]);
    
    int isVowel(char a)
    {
        int i;
        for (i = 0; i < NUM_VOWELS; i++)
        {
            if (a == VOWELS[i])
            {
                return 1;
            }
        }
        
        return 0;
    }
    
    char* reverseVowels(char* s) 
    {
        int i,j;
        int iVowel, jVowel;
        char temp;
        
        if (!s)
        {
            return s;
        }
        
        for (i = 0, j = strlen(s) - 1; i < j; )
        {
            iVowel = isVowel(s[i]);
            jVowel = isVowel(s[j]);
            
            if (iVowel && jVowel)
            {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
            
            if (iVowel)
            {
                i++;
            }
            
            if (jVowel)
            {
                j--;
            }
        }
        
        return s;
    }

  • 0
    K

    Your code is getting stuck in an infinite loop.

    You have to increment 'i' and decrement 'j' after you swap in case of a vowel.

    if (iVowel && jVowel)
            {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
                 /// missing i++ and j--
            }
    

  • 0
    A

    Thank you! I changed the logic to account for all 4 cases


Log in to reply
 

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