-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeCheck.java
75 lines (62 loc) · 1.74 KB
/
PalindromeCheck.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package string;
/**
* Program includes three methods of checking if a string is a valid palindrome.
*
* @author Tzipora Ziegler
* @see <a https://en.wiktionary.org/wiki/Appendix:English_palindromes">Wiktionary list of palindromes</a>
*/
public class PalindromeCheck {
/**
* Uses a while loop to test if the text is a valid palindrome
*
* @param text The string to test if is a palindrome
* @return Returns whether the text is a valid palindrome
*/
public boolean whileCheck(String text) {
if (text == null || text.length() < 2) {
return false;
}
int startIndex = 0;
int endIndex = text.length() - 1;
while (endIndex > startIndex) {
if (text.charAt(startIndex) != text.charAt(endIndex)) {
return false;
}
endIndex--;
startIndex++;
}
return true;
}
/**
* Uses StringBuilder's reverse() method to test if the text is a valid palindrome
*
* @param text The string to test if is a palindrome
* @return Returns whether the text is a valid palindrome
*/
public boolean stringBuilderCheck(String text) {
if (text == null || text.length() < 2) {
return false;
}
final StringBuilder builder = new StringBuilder(text);
return text.equals(builder.reverse().toString());
}
/**
* Uses a for loop to test if the text is a valid palindrome
*
* @param text The string to test if is a palindrome
* @return Returns whether the text is a valid palindrome
*/
public boolean forLoopCheck(String text) {
if (text == null || text.length() < 2) {
return false;
}
final int endIndex = text.length() - 1;
final int middleIndex = text.length() / 2;
for (int i = 0; i <= middleIndex; i++) {
if (text.charAt(i) != text.charAt(endIndex - i)) {
return false;
}
}
return true;
}
}