-
Notifications
You must be signed in to change notification settings - Fork 109
/
Palindrome.java
56 lines (43 loc) · 1.64 KB
/
Palindrome.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
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// *******************************************************************
// Palindrome.java Reads in a string and prints a message saying whether it
// is a palindrome.
// *******************************************************************
String testString;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
testString = scan.nextLine();
if (palindrome(testString)) {
System.out.println("It's a palindrome!");
} else {
System.out.println("It's not a palindrome.");
}
}
// ----------------------------------------------------------
// Recursively determines whether s is a palindrome.
// It is if
// -- it's 0 or 1 char in length, or
// -- the first and last letters are the same and the
// string without those letters is also a palindrome
// ----------------------------------------------------------
private static boolean palindrome(String s) {
if (s.length() == 0 || s.length() == 1) {
return true;
}
if (s.charAt(0) != s.charAt(s.length() - 1)) {
return false;
}
return palindrome(s.substring(1, s.length() - 1));
}
// CREATE A INTEGER length THAT STORES THE LENGTH OF THE STRING PARAMETER s
// 1) TEST IF length IS GREATER THAN 1 -
// 2) IF length IS GREATER THAN 1, CHECK IF THE FIRST CHARACTER OF s IS EQUAL TO
// THE CHARACTER AT length - 1
// 3) IF THE CHARACTERS ARE EQUAL, TEST THE NEXT SET OF CHARACTERS (MAKE A
// RECURSIVE
// CALL AND TEST THE VALUE THAT IS RETURNED)
// 4) IF NONE OF THESE TEST CASES ARE true, RETURN false
// (HINT: YOU SHOULD RETURN false 3 TIMES)
}