Skip to content

Instantly share code, notes, and snippets.

@ali-alaei
Created November 2, 2021 09:55
Show Gist options
  • Save ali-alaei/bb375b7159c6eeb5b039ea30bcaa633e to your computer and use it in GitHub Desktop.
Save ali-alaei/bb375b7159c6eeb5b039ea30bcaa633e to your computer and use it in GitHub Desktop.
class Solution
{
//The function checks if a substring with given start and end points
//is a palindrome or not.
public boolean isPalindrome(String s, int start, int end)
{
while (start < end)
{
if (s.charAt(start) != s.charAt(end))
return false;
start++;
end--;
}
return true;
}
public boolean validPalindrome(String s)
{
int start = 0, end = s.length() - 1;
//while the two start and end pointers do not collide,
//enter the while loop
while (start < end)
{
//If two characters are equal, we move the start pointer forward
//and the end pointer backward
if (s.charAt(start) == s.charAt(end))
{
start++;
end--;
}
//If the two characters are not equal, enters else
else
{
//The if block checks whether or not a palindrome exists after deleting
//at most one character from the start or the end of the substring
//by calling the isPalindrome function
if (isPalindrome(s, start + 1, end) || isPalindrome(s, start, end - 1))
return true;
//If it returns false, the string is not a palindrome
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment