[LeetCode] Valid Palindrome II

문제

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

풀이

2020 01 09 20 20 31 문자열을 양옆 포인터로 검사를 하면서, 문자가 달라졌을때 왼쪽문자를 지운 문자열과 오른쪽 문자를 지운 문자열 2개를 준비해서 각 문자열이 팰린드롬인지 아닌지 판단하면 되는 문제이다.

/**
 * @param {string} s
 * @return {boolean}
 */

const isPalindrome = str => {
	for (let i = 0; i <= str.length / 2; i++) {
		if (str[i] !== str[str.length - 1 - i]) return false;
	}
	return true;
};

var validPalindrome = function(s) {
	for (let i = 0; i <= s.length / 2; i++) {
		const left = i;
		const right = s.length - 1 - i;

		if (s[left] !== s[right]) {
			const str1 = s.slice(left, right);
			const str2 = s.slice(left + 1, right + 1);

			if (!isPalindrome(str1) && !isPalindrome(str2)) return false;
			return true;
		}
	}
	return true;
};

결과

2020 01 09 20 21 47

출처

https://leetcode.com/problems/valid-palindrome-ii/

Loading script...