Palindrome Index

  • + 0 comments

    My answer with Typescript, both worked.

    First attemp that simple

    function palindromeIndex1(s: string): number {
        // function check string [s] is palidrome
        const isPalindrome = (s: string): boolean => {
            for (let i = 0; i < Math.floor(s.length / 2); i++) {
                let ri = s.length - i - 1
                if (s[i] != s[ri]) return false
            }
            return true
        }
    
        // 1. check [s] isn't palindrome already
        if (!isPalindrome(s)) {
            // 2. loop [s]...
            for (let i = 0; i < s.length; i++)
                // 3. remove each character by [i], check remain [s] is palindrome
                if (isPalindrome(s.slice(0, i) + s.slice(i + 1)))
                    // 4. found palindrome, return [i]
                    return i
        }
    
        // 4. [s] alreay palidome, return -1
        return -1;
    }
    

    Second attemp is optimal

    function palindromeIndex(s: string): number {
        // function check string [s] is palidrome
        const isPalindrome = (start: number, end: number): boolean => {
            while (start < end) {
                if (s[start] != s[end]) return false;
                start++;
                end--;
            }
            return true;
        }
    
        /**
         * solution 1 works fine but it seems to be suboptimal.
         * new idea is define 2 index at start and end of [s], reduce to middle.
         * only check 2 case when non palindrome found
         * + case1: start removed
         * + case2: end removed
         * orelse non of [s] can be palindrome, return -1
         */
    
        // 1. define [start] and [end]
        let start = 0
        let end = s.length - 1
    
        // 2. loop ... recude [start] and [end] to middle
        while (start < end) {
            // 3. if [s] at [start] and [end] is not equal, mean not palidrome at [start] to [end]
            if (s[start] != s[end]) {
                // 4.1 try remove [start], check palidrome ... return if found
                if (isPalindrome(start + 1, end)) return start
                // 4.2 try remove [end], check palidrome ... return if found
                if (isPalindrome(start, end - 1)) return end
            }
            start++
            end--
        }
    
        // [start] and [end] go throuth [s] but palidrome not found, return -1
        return -1;
    }