-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLast2.java
More file actions
30 lines (24 loc) · 711 Bytes
/
Last2.java
File metadata and controls
30 lines (24 loc) · 711 Bytes
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
package Warmup2;
public class Last2 {
/*
* https://codingbat.com/prob/p178318 Given a string, return the count of the
* number of times that a substring length 2 appears in the string and also as
* the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end
* substring).
*
* last2("hixxhi") → 1 last2("xaxxaxaxx") → 1 last2("axxxaaxx") → 2
*/
public int last2(String str) {
if (str.length() < 2)
return 0;
String end = str.substring(str.length() - 2);
int count = 0;
for (int i = 0; i < str.length() - 2; i++) {
String sub = str.substring(i, i + 2);
if (sub.equals(end)) { // Use .equals() with strings
count++;
}
}
return count;
}
}