diff --git a/core-java/src/main/java/com/baeldung/string/Palindrome.java b/core-java/src/main/java/com/baeldung/string/Palindrome.java index e339d92447..37284a5424 100644 --- a/core-java/src/main/java/com/baeldung/string/Palindrome.java +++ b/core-java/src/main/java/com/baeldung/string/Palindrome.java @@ -8,7 +8,33 @@ public class Palindrome { int forward = 0; int backward = length - 1; boolean palindrome = true; - while ((backward > forward)?(palindrome=(text.charAt(forward++) == text.charAt(backward--))):false); + while (backward > forward) { + char forwardChar = text.charAt(forward++); + char backwardChar = text.charAt(backward--); + if (forwardChar != backwardChar) + return false; + } return palindrome; } + + public boolean isPalindromeReverseTheString(String text) { + String reverse = ""; + text = text.toLowerCase(); + char[] plain = text.toCharArray(); + for (int i = plain.length - 1; i >= 0; i--) + reverse += plain[i]; + return reverse.equals(text); + } + + public boolean isPalindromeUsingStringBuilder(String text) { + StringBuilder plain = new StringBuilder(text); + StringBuilder reverse = plain.reverse(); + return reverse.equals(plain); + } + + public boolean isPalindromeUsingStringBuffer(String text) { + StringBuffer plain = new StringBuffer(text); + StringBuffer reverse = plain.reverse(); + return reverse.equals(plain); + } } diff --git a/core-java/src/test/java/com/baeldung/string/WhenCheckingPalindrome.java b/core-java/src/test/java/com/baeldung/string/WhenCheckingPalindrome.java index 691d74c751..eeaed09fff 100644 --- a/core-java/src/test/java/com/baeldung/string/WhenCheckingPalindrome.java +++ b/core-java/src/test/java/com/baeldung/string/WhenCheckingPalindrome.java @@ -34,4 +34,40 @@ public class WhenCheckingPalindrome { for(String sentence:sentences) Assert.assertTrue(palindrome.isPalindrome(sentence)); } + + @Test + public void whenReverseWord_shouldBePalindrome() { + for(String word:words) + Assert.assertTrue(palindrome.isPalindromeReverseTheString(word)); + } + + @Test + public void whenReverseSentence_shouldBePalindrome() { + for(String sentence:sentences) + Assert.assertTrue(palindrome.isPalindromeReverseTheString(sentence)); + } + + @Test + public void whenStringBuilderWord_shouldBePalindrome() { + for(String word:words) + Assert.assertTrue(palindrome.isPalindromeUsingStringBuilder(word)); + } + + @Test + public void whenStringBuilderSentence_shouldBePalindrome() { + for(String sentence:sentences) + Assert.assertTrue(palindrome.isPalindromeUsingStringBuilder(sentence)); + } + + @Test + public void whenStringBufferWord_shouldBePalindrome() { + for(String word:words) + Assert.assertTrue(palindrome.isPalindromeUsingStringBuffer(word)); + } + + @Test + public void whenStringBufferSentence_shouldBePalindrome() { + for(String sentence:sentences) + Assert.assertTrue(palindrome.isPalindromeUsingStringBuffer(sentence)); + } }