CC-11 : Check Palindrome.
Description:
A palindrome is a sequence of letters that are when read same backward or forward, for example check the String “madam”. Given input String str, check if it a palindrome or not.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| str="rotator" | The input string is a palindrome. |
| str="madam"; | The input string is a palindrome. |
| str="bood" | The input string is *not* a palindrome. |
Pseudocode:
| The java method should accept following input parameters: str (String). |
| Trim the leading and training spaces of str using String.trim() method. |
| For ease of character matching convert the characters of input str to lower case using String.toLowercase() method. |
| Initialize char array chars=str.toCharArray(). |
| Initialize integer variable left to 0. Initialize integer variable right to chars.length-1. We will use these variables to traverse and match the characters in chars. Initially left is 0 and right is index of the last character, so we can compare the same. In the next iteration left will be incremented by 1 and right we will be decremented by 1 and we can gain compare these two characters and so on. For str to be a palindrome, characters at each iteration should be the same. |
| Iterate through chars using while loop till left < right:
If chars[left] != chars[right], then the characters do not match and the string is not a palindrome, return false from the program.
If chars[left] == chars[right]:
Increment left by one.
Decrement right by one.
|
| If at the end of the above while loop if the program has not exited due to mismatch, this means str is a palindrome. Return true from the program. |
The above algorithm can also be completed using Java String APIs:
| Refer code below. The only difference while using String APIs is that we do not extract characters from str. We use String.CharAt() method to access characters at various indexes for comparison. Rest of the algorithm remains the same. |
Code:
public boolean stringCheckPalindrome(String str) {
str=str.trim().toLowerCase();
char[] chars=str.toCharArray();
int left=0; int right=str.length()-1;
while (left < right) {
if (chars[left] != chars[right]) {
return false;
}else {
left++;
right--;
}
}
return true;
}
public boolean stringCheckPalindromeWithAPI(String str) {
str=str.trim().toLowerCase();
int left=0; int right=str.length()-1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}else {
left++;
right--;
}
}
return true;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |