Palindrome Index

  • + 0 comments
    by C:
    int palindromeIndex(char* s) {
    
        int len=0, left=0, right=len-1, tempLeft=0, tempRight=len-1;
        if(s != NULL) {
            while(s[len]!='\0') len++;
            right=len-1;
            tempRight=len-1;
    
            // normal checking
            while(left<right && (s[left]==s[right])) {
                left++;
                right--;
            }
            if(left>=right) return -1;
    
            // try to skip left
            tempLeft = left++;
            tempRight = right;
            while(left<right &&(s[left]==s[right])) {
                left++;
                right--;
            }
            if(left>=right) return tempLeft;
    
            // try to skip right ,BUT need first to back to the old value
            left = tempLeft;
            right = tempRight-1;
            while(left<right && (s[left]==s[right])) {
                left++;
                right--;
            }
            if(left>=right) return tempRight;
            else
                return -1; // so no solution for this string
    
        } else {
            return -1;
        }
    
    
    }