forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecurse.java
More file actions
83 lines (68 loc) · 1.82 KB
/
Copy pathRecurse.java
File metadata and controls
83 lines (68 loc) · 1.82 KB
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
76
77
78
79
80
81
82
83
import java.util.Scanner;
/**
* Recursion exercise.
*/
public class Recurse {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a word (all lowercase, no spaces): ");
String s = in.nextLine();
System.out.println(isPalindrome(s));
}
/**
* Returns the first character of the given String.
*/
public static char first(String s) {
return s.charAt(0);
}
/**
* Returns all but the first letter of the given String.
*/
public static String rest(String s) {
return s.substring(1);
}
/**
* Returns all but the first and last letter of the String.
*/
public static String middle(String s) {
return s.substring(1, s.length() - 1);
}
/**
* Returns the length of the given String.
*/
public static int length(String s) {
return s.length();
}
public static void printString(String s) {
int len = length(s);
for (int i = 0; i < len; i++) {
System.out.println(first(s));
s = rest(s);
}
}
public static String reverseString(String s) {
String reverse = "";
int len = length(s);
for (int i = 0; i < len; i++) {
reverse = first(s) + reverse;
s = rest(s);
}
return reverse;
}
public static boolean isPalindrome(String s) {
if (length(s) == 1) {
return true;
}
else if (length(s) == 2 && first(s) == first(reverseString(s))) {
return true;
}
else {
if (first(s) == first(reverseString(s))) {
return isPalindrome(middle(s));
}
else {
return false;
}
}
}
}