File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments