File tree Expand file tree Collapse file tree
main/java/com/baeldung/string
test/java/com/baeldung/string Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -8,7 +8,33 @@ public boolean isPalindrome(String text) {
88 int forward = 0 ;
99 int backward = length - 1 ;
1010 boolean palindrome = true ;
11- while ((backward > forward )?(palindrome =(text .charAt (forward ++) == text .charAt (backward --))):false );
11+ while (backward > forward ) {
12+ char forwardChar = text .charAt (forward ++);
13+ char backwardChar = text .charAt (backward --);
14+ if (forwardChar != backwardChar )
15+ return false ;
16+ }
1217 return palindrome ;
1318 }
19+
20+ public boolean isPalindromeReverseTheString (String text ) {
21+ String reverse = "" ;
22+ text = text .toLowerCase ();
23+ char [] plain = text .toCharArray ();
24+ for (int i = plain .length - 1 ; i >= 0 ; i --)
25+ reverse += plain [i ];
26+ return reverse .equals (text );
27+ }
28+
29+ public boolean isPalindromeUsingStringBuilder (String text ) {
30+ StringBuilder plain = new StringBuilder (text );
31+ StringBuilder reverse = plain .reverse ();
32+ return reverse .equals (plain );
33+ }
34+
35+ public boolean isPalindromeUsingStringBuffer (String text ) {
36+ StringBuffer plain = new StringBuffer (text );
37+ StringBuffer reverse = plain .reverse ();
38+ return reverse .equals (plain );
39+ }
1440}
Original file line number Diff line number Diff line change @@ -34,4 +34,40 @@ public void whenSentence_shouldBePalindrome() {
3434 for (String sentence :sentences )
3535 Assert .assertTrue (palindrome .isPalindrome (sentence ));
3636 }
37+
38+ @ Test
39+ public void whenReverseWord_shouldBePalindrome () {
40+ for (String word :words )
41+ Assert .assertTrue (palindrome .isPalindromeReverseTheString (word ));
42+ }
43+
44+ @ Test
45+ public void whenReverseSentence_shouldBePalindrome () {
46+ for (String sentence :sentences )
47+ Assert .assertTrue (palindrome .isPalindromeReverseTheString (sentence ));
48+ }
49+
50+ @ Test
51+ public void whenStringBuilderWord_shouldBePalindrome () {
52+ for (String word :words )
53+ Assert .assertTrue (palindrome .isPalindromeUsingStringBuilder (word ));
54+ }
55+
56+ @ Test
57+ public void whenStringBuilderSentence_shouldBePalindrome () {
58+ for (String sentence :sentences )
59+ Assert .assertTrue (palindrome .isPalindromeUsingStringBuilder (sentence ));
60+ }
61+
62+ @ Test
63+ public void whenStringBufferWord_shouldBePalindrome () {
64+ for (String word :words )
65+ Assert .assertTrue (palindrome .isPalindromeUsingStringBuffer (word ));
66+ }
67+
68+ @ Test
69+ public void whenStringBufferSentence_shouldBePalindrome () {
70+ for (String sentence :sentences )
71+ Assert .assertTrue (palindrome .isPalindromeUsingStringBuffer (sentence ));
72+ }
3773}
You can’t perform that action at this time.
0 commit comments