CodeLab Solution 20861




CS125 CodeLab Solutions

CodeLab Solution 20861

A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string ). Write a recursive, boolean -valued method , isPalindrome that accepts a string and returns whether the string is a palindrome.

A string , s, is a palindrome if:

s is the empty string or s consists of a single letter (which reads the same back or forward), or
the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters ) form a palindrome.

[cc lang=”JAVA”] public static boolean isPalindrome(String str) {
if (str.length() > 1) {

char begin = str.charAt(0);
char end = str.charAt(str.length() – 1);

if (begin != end) {
return false;
}

StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length() – 1);

if (!isPalindrome(sb.toString())) {
}
}

return true;
}
[/cc]


No Comments Yet.

Leave a comment

You must be Logged in to post a comment.