Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.fhnw.claudemartin;
- public class SomeClass {
- public static void main(final String[] args) {
- test("", true);
- test("12345", false);
- test("racecar", true);
- test("Madam", false);
- test("abcdefgfedcba", true);
- test("abcdefggfedcba", true);
- test("abcdefggxfedcba", false);
- // one symbol in two chars (surrogate pair):
- final String clef = "\uD834\uDD1E";
- test(clef + clef, true);
- }
- static void test(final String a, final boolean expected) {
- final boolean actual = testPalindrome(a);
- (actual == expected ? System.out : System.err).format("'%s' => %s%n", a, actual);
- }
- /**
- * is the given string a palindrome?
- *
- * Note: this doesn't work with surrogate pairs.
- *
- * @param str
- * the string to be tested
- * @return true if it's a palindrome.
- */
- public static boolean testPalindrome(final String str) {
- final int last = str.length() - 1;
- if (-1 == last)
- return true;
- return testPalindrome(str, 0, last);
- }
- private static boolean testPalindrome(final String str, final int offset, final int last) {
- if (str.charAt(offset) != str.charAt(last - offset))
- return false;
- if (offset == last / 2)
- return true;
- return testPalindrome(str, 1 + offset, last);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement