Palindrome Index

  • + 0 comments

    Perl solution:

    sub is_palindrome {
        my ($st, $left_s, $right_s) = @_;
        while ($left_s < $right_s) {
            return 0 if substr($st, $left_s, 1) ne substr($st, $right_s, 1);
            $left_s++;
            $right_s--;
        }
        return 1;
    }
    
    sub palindromeIndex {
        my $s = shift;
        my $left_side = 0;
        my $right_side = length($s) - 1;
    
        while ($left_side < $right_side) {
            if (substr($s, $left_side, 1) ne substr($s, $right_side, 1)) {
                if (is_palindrome($s, $left_side + 1, $right_side)) {
                    return $left_side;
                } elsif (is_palindrome($s, $left_side, $right_side - 1)) {
                    return $right_side;
                } else {
                    return -1;
                }
            }
            $left_side++;
            $right_side--;
        }
        return -1;
    }