Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7fc1579

Browse files
Add solution for Substrings That Begin and End With the Same Letter
1 parent d3038a8 commit 7fc1579

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ Algorithm exercises from LeetCode implemented in Java v11.
100100

101101
### Prefix Sum
102102
- Product of the Last K Numbers | [Problem](https://leetcode.com/problems/product-of-the-last-k-numbers) | [Solution](src/solutions/ProductOfNumbers.java)
103+
- Substrings That Begin and End With the Same Letter | [Problem](https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter) | [Solution](src/solutions/SubstringsWithSameLetter.java)
103104

104105
### Recursion
105106
- Closest Binary Search Tree Value | [Problem](https://leetcode.com/problems/closest-binary-search-tree-value)
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package solutions;
2+
3+
// [Problem] https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter
4+
class SubstringsWithSameLetter {
5+
// Prefix sum
6+
// O(n) time, O(1) space
7+
public long numberOfSubstrings(String s) {
8+
int[] letterCounts = new int[26];
9+
long substringCount = 0;
10+
for (int i = 0; i < s.length(); i++) {
11+
char c = s.charAt(i);
12+
int letterCount = ++letterCounts[c - 'a'];
13+
substringCount += letterCount;
14+
}
15+
return substringCount;
16+
}
17+
18+
// Test
19+
public static void main(String[] args) {
20+
SubstringsWithSameLetter solution = new SubstringsWithSameLetter();
21+
22+
String input1 = "abcba";
23+
long expectedOutput1 = 7;
24+
long actualOutput1 = solution.numberOfSubstrings(input1);
25+
System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1));
26+
27+
String input2 = "abacad";
28+
long expectedOutput2 = 9;
29+
long actualOutput2 = solution.numberOfSubstrings(input2);
30+
System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2));
31+
}
32+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /