Skip to content

Commit 57fb070

Browse files
feat(recursion-solutions): add count substrings with matching start and end
1 parent bdb883b commit 57fb070

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
PROBLEM:
3+
Count substrings that start and end with same character.
4+
5+
APPROACH:
6+
Use recursion with shrinking window.
7+
Compare first and last characters.
8+
*/
9+
10+
public class CountSubstrings {
11+
12+
public static int count(String str, int i, int j) {
13+
if (i > j) {
14+
return 0;
15+
}
16+
17+
if (i == j) {
18+
return 1;
19+
}
20+
21+
int res = count(str, i + 1, j)
22+
+ count(str, i, j - 1)
23+
- count(str, i + 1, j - 1);
24+
25+
if (str.charAt(i) == str.charAt(j)) {
26+
res++;
27+
}
28+
29+
return res;
30+
}
31+
32+
public static void main(String[] args) {
33+
String str = "aba";
34+
System.out.println(count(str, 0, str.length() - 1));
35+
}
36+
}

0 commit comments

Comments
 (0)