String
and returns a boolean
-> true
if the input String
is a palindrome and false
if it is not. An empty string and a null input are considered palindromes. You also need to account for the space character. For example, "race car" should return false
as read backward it is "rac ecar".
isStringPalindrome("madam") -> true
isStringPalindrome("aabb") -> false
isStringPalindrome("race car") -> false
isStringPalindrome("") -> true
isStringPalindrome(null) -> true
Use two iterators, one for traversing the characters of the String
from the first index to the middle and the other from last index to the middle - moving backward. Compare the characters at each step to determine if the input is a palindrome.
charAt(i)
method of the String
class useful.
for
loop from 0
to length/2
i
th position) with its corresponding 'mirror' character at the length-1-i
th position.
str.charAt(i) != str.charAt(l-1-i)
, i.e. if the first and last characters moving inwards are not equal, return false
String
is a palindrome. Return true
.
public static boolean isStringPalindrome(String str){ }
C
Java
Python