This is a classical problem asked in mostly all the interviews.
I am posting the solution in Javascript, you can convert it in the language of your own choice.
Algo:
- Use two pointers (left & right)
- Put left at the start of string and right at the end of string
- Check the value at pointer and take decision on the basis of equality
- Move the pointers towards each other
- Until left is smaller than equal to right
Code:
const isPalindrome = function(A){
A = A.replace(/[^0-9a-zA-Z]/g, "");
A = A.toLowerCase();
var left = 0
var right = A.length; - 1;
while(left <= right) {
if(A[left] !== A[right]) {
return 0
}
left++;
right--;
}
return 1;
}
Note: In the above solution I have omitted the special characters and spaces.
Feel free to post suggestions or more efficient code
Top comments (4)
I think this is way easier:
Sure, it is less code, but each function split, reverse, join will be executing a traversal, which will be 3 loops.
While it can be achieved in a single loop.
Is there a way to find longest palindrome string from a given string?
Yes you can do that, make sliding window, on the string and increase the window until the the palindrome function returns false.
It is same like finding a sub array with maximum sum.
Google for Sliding window algos.