680. Valid Palindrome II
Tags:
Easy
Skills:
Two pointer
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu kiểm tra xem một chuỗi có thể trở thành palindrome (chuỗi đối xứng) sau khi xóa tối đa một ký tự hay không?
Approach
Time and space complexity
isPalindrome chạy trong O(n) với n là độ dài của chuỗi.Solution
1function validPalindrome(s: string): boolean {
2 function isPaindrome(str: string, left: number, right: number): boolean {
3 while(left < right) {
4 if(str[left] !== str[right]) {
5 return false;
6 }
7
8 left++;
9 right--
10 }
11 return true;
12 }
13
14 let left = 0;
15 let right = s.length - 1;
16
17 while(left < right) {
18 if(s[left] !== s[right]) {
19 return (
20 isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1)
21 )
22 }
23 left++;
24 right--
25 }
26
27 return true;
28};