Valid Palindrome IV
You are given a 0-indexed string s consisting of only lowercase English letters. In one operation, you can change any character of s to any other character. Return true if you can make s a palindrome after performing exactly one or two operations, or return false otherwise. |
Simply use the two pointer approach to check if string is a palindrome
– Start comparing first and last character
– If there’s a mismatch (i.e. characters are different), add ‘1’ to the mismatch count. What does this mean? It means changing any one of the characters to the other will cause the string to be a (potential) palindrome.
– At the end if `(mismatch_count is <= 2) ? true : false`
/** * @param {string} s * @return {boolean} */ var makePalindrome = function(s) { let i = 0; let j = s.length - 1; let mismatch = 0; while ( i < j ) { if (s[i++] === s[j--]) continue; mismatch++; if (mismatch > 2) return false; } return mismatch <= 2; }; |