680. Valid Palindrome II(Solution || Leetcode easy || Java)

Palakkgoyal
1 min readNov 27, 2022

--

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Example 1:

Input: s = "aba"
Output: true

Example 2:

Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.

Example 3:

Input: s = "abc"
Output: false

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.

SOLUTION:

class Solution {
public boolean validPalindrome(String s) {
//Set two pointers to check its a palindrome or not
int a = 0;
int b = s.length() - 1;

while(a <= b){
//if the elements do not match call the other method to check after
//any one from the two that don't match, if the string become a
//palindrome or not and return the result
if(s.charAt(a) != s.charAt(b)){
return check(s,a+1,b) || check(s,a,b-1);
}

a++; b--;
}

return true;
}

public boolean check(String s, int a, int b){

while(a <= b){
if(s.charAt(a) != s.charAt(b)){
return false;
}
a++; b--;
}

return true;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet