如果你反转字符串并且它仍然等于它自己,这意味着它是一个回文。以下是我将如何实现它:
package com.sandbox;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class PalindromeTest {
@Test
public void testTheseArePalindromes() {
assertTrue(isPalindrome("abccba"));
assertTrue(isPalindrome("121"));
assertTrue(isPalindrome("Malayalam"));
assertTrue(isPalindrome("peeweep"));
assertTrue(isPalindrome("123 321"));
}
@Test
public void testTheseAreNOTPalindromes() {
assertFalse(isPalindrome("abc"));
assertFalse(isPalindrome("123"));
assertFalse(isPalindrome("123 123"));
}
private boolean isPalindrome(String input) {
String lowerIn = input.toLowerCase();
String reversed = StringUtils.reverse(lowerIn);
return lowerIn.equals(reversed);
}
}
此页面上的短语也是回文。它必须对那些起作用吗?如果是这样,这是一个非常简单的更改:
package com.sandbox;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
public class PalindromeTest {
@Test
public void testTheseArePalindromes() {
assertTrue(isPalindrome("abccba"));
assertTrue(isPalindrome("121"));
assertTrue(isPalindrome("Malayalam"));
assertTrue(isPalindrome("peeweep"));
assertTrue(isPalindrome("123 321"));
assertTrue(isPalindrome("A dog, a plan, a canal: pagoda."));
assertTrue(isPalindrome("A man, a plan, a canal: Panama."));
assertTrue(isPalindrome("A tin mug for a jar of gum, Nita."));
}
@Test
public void testTheseAreNOTPalindromes() {
assertFalse(isPalindrome("abc"));
assertFalse(isPalindrome("123"));
assertFalse(isPalindrome("123 123"));
}
private boolean isPalindrome(String input) {
String removedPunctuation = input.toLowerCase().replaceAll("[.,;: \t]", "");
String reversed = StringUtils.reverse(removedPunctuation);
return removedPunctuation.equals(reversed);
}
}