DoggettCK

DoggettCK DoggettCK

Niner since 2005

Comments

  • Gary Daniels and Evan Goldring - Mock whiteboard problem

    Here's what I came up with in a few minutes. It should run in linear time and in-place. Not sure if it will work with TCHARs yet, so I'll give that a shot in a few minutes.

    bool isAlphaNumeric(char c)
    {
        if(iswalpha(c) || iswdigit(c)) return true;
        return false;    
    }
    
    bool isPalindrome(char *str)
    {
        if(*str == '\0')
        {
            return false;    
        }
        int len = strlen(str);
        if(len <= 1) return true; // 0- or 1-length strings are simplest palindromes
        
        char *start = str;
        char *end = start + strlen(str) - 1;
        
        while(start < end)
        {
            // if start not a char, increment start and continue
            if(!isAlphaNumeric(*start))
            {
                *start++;
                continue;    
            }
            // if end not a char, decrement end and continue
            if(!isAlphaNumeric(*end))
            {
                *end--;
                continue;    
            }
            // if two characters are not equal, return false
            if(towlower(*start) != towlower(*end)) return false;
            // otherwise start++, end--
            *start++;
            *end--;        
        }
        return true;
    }
    


    Edit: Yup, substituting TCHAR for char works just fine. And just for the hell of it, here's strrev (or revstr, to avoid name conflicts)

    void revstr(TCHAR *str)
    {
        if(*str == '\0')
        {
            return;    
        }
        
        TCHAR *start = str;
        TCHAR *end = start + strlen(str) - 1;
        
        while(start < end)
        {
            *start ^= *end;
            *end ^= *start;
            *start ^= *end;
            *start++;
            *end--;
            // could also use *start ^= *end ^= *start++ ^= *end-- if you want to get fancy
        }    
    }