Check whether string is palindrome or not
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (1760)

Write a function to check that given string is palindrome or not.


Posted Answers

A string is a palindrome if it can be read the same way in either forward or reverse direction. \( e.g \), `\( kayak \)'. It reads the same (\( k \) - \( a \) - \( y \) - \( a \) - \( k \)) from either direction. The algorithm works as :


  • Initialize two pointers - one from the beginning of the string and the other from the end.
  • Compare the characters in both the pointers until the first pointer is less than the second one.
  • If they are same, increment the first pointer and decrement the second one.
  • If they are not same, return false.

Time complexity = \( O(n) \).

public boolean checkStringIsPalindrome(String input){

/* Initialize first ponter */
int pointer1 = 0;
/* Initialize second ponter */
int pointer2 = input.length - 1;

while(pointer1 < pointer2){
/* check the characters at the two pointers */
/* Ignore white space */
if(input.charAt(pointer1) == ' ')
pointer1++;
if(input.charAt(pointer2) == ' ')
pointer2--;

/* If the characters at the two pointers does not match - Not a
palindrome */
if(input.charAt(pointer1) != input.charAt(pointer2)){
return false;
break;
}else{
pointer1++;
pointer2--;
}
}
/* Yes, its a palindrome */
return true;
}


< Better approach > Using one pointer variable

public boolean checkStringIsPalindrome(String input){
for (int i = 0;i < input.length / 2) + 1; ++i){
if (input.charAt(i) != input.charAt(input.length - i - 1))
return false;
}
return true;
}

You need to Sign In to post your solution.