Palindrome Index

  • + 0 comments
    function palindromeIndex(s) {
        let left = 0, right = s.length - 1
        while (left <= right) {
            if (s[left] !== s[right]) {
                if (isPalindrome(s.substring(left, right))) return right
                else if (isPalindrome(s.substring(left + 1, right + 1))) return left
                return -1
            } else {
                left++
                right--
            }
        }
        return -1
    }
    
    function isPalindrome(s) {
        for (let i = 0; i < Math.floor(s.length / 2); i++) {
            if (s[i] !== s[s.length - 1 - i]) return false
        }
        return true
    }