LeetCode 3084: Count Substrings Starting and Ending with Given Character Solution
Master LeetCode problem 3084 (Count Substrings Starting and Ending with Given Character), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we can iterate over the string s and count the number of occurrences where the character at the current index is equal to the given character c. For each occurrence, we can count the number of substrings that start and end with c by multiplying the number of characters before and after the current index that are equal to c.
Solution Code
class Solution {
public int countSubstrings(String s, char c) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
int leftCount = 1;
int j = i - 1;
while (j >= 0 && s.charAt(j) != c) {
leftCount++;
j--;
}
int rightCount = 1;
j = i + 1;
while (j < s.length() && s.charAt(j) != c) {
rightCount++;
j++;
}
count += leftCount * rightCount;
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3084 (Count Substrings Starting and Ending with Given Character)?
This page provides optimized solutions for LeetCode problem 3084 (Count Substrings Starting and Ending with Given Character) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3084 (Count Substrings Starting and Ending with Given Character)?
The time complexity for LeetCode 3084 (Count Substrings Starting and Ending with Given Character) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3084 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3084 in Java, C++, or Python.