Skip to content

Commit edd4f88

Browse files
committed
added doubloon examples
1 parent fad746b commit edd4f88

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

ch07/Doubloon.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Example from the end of Chapter 7.
3+
*/
4+
public class Doubloon {
5+
6+
public static boolean isDoubloon(String s) {
7+
8+
// count the number of times each letter appears
9+
int[] counts = new int[26];
10+
String lower = s.toLowerCase();
11+
for (char letter : lower.toCharArray()) {
12+
int index = letter - 'a';
13+
counts[index]++;
14+
}
15+
16+
// determine whether the given word is a doubloon
17+
for (int count : counts) {
18+
if (count != 0 && count != 2) {
19+
return false;
20+
}
21+
}
22+
return true;
23+
}
24+
25+
public static void main(String[] args) {
26+
System.out.println(isDoubloon("Mama"));
27+
System.out.println(isDoubloon("Lama"));
28+
}
29+
30+
}

ch07/Inefficient.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Version of Doubloon that uses nested loops.
3+
*/
4+
public class Inefficient {
5+
6+
public static boolean isDoubloon(String s) {
7+
8+
// count the number of times each letter appears
9+
s = s.toLowerCase();
10+
for (char c = 'a'; c <= 'z'; c++) {
11+
int count = 0;
12+
for (int i = 0; i < s.length(); i++) {
13+
if (s.charAt(i) == c) {
14+
count++;
15+
}
16+
}
17+
18+
// determine whether the word is a doubloon
19+
if (count != 0 && count != 2) {
20+
return false; // not a doubloon
21+
}
22+
}
23+
return true; // all counts were 0 or 2
24+
}
25+
26+
public static void main(String[] args) {
27+
System.out.println(isDoubloon("Mama"));
28+
System.out.println(isDoubloon("Lama"));
29+
}
30+
31+
}

0 commit comments

Comments
 (0)