Problem Description
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
Key Insights
- A substring is defined as a contiguous sequence of characters within a string.
- To find substrings that start and end with a specific character, we need to identify all occurrences of that character in the string.
- The number of valid substrings can be calculated using the positions of these occurrences.
- If there are n occurrences of the character c, the total number of substrings that can be formed is given by the formula: n * (n + 1) / 2.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s, since we may need to traverse the string once to count occurrences. Space Complexity: O(1), as we are using a constant amount of extra space.
Solution
To solve the problem, we can follow these steps:
- Initialize a count variable to track the occurrences of the character c in the string.
- Traverse the string and increment the count each time we encounter c.
- Use the formula n * (n + 1) / 2 to compute the total number of substrings that can be formed with these occurrences.
This approach ensures that we efficiently count the required substrings without generating them explicitly.