LeetCode 2489: Number of Substrings With Fixed Ratio
Problem Description
Explanation:
Given a string of digits and a fixed ratio, we need to find the number of substrings with a fixed ratio. A substring is considered valid if the ratio of the number of 0's to the number of 1's is equal to the fixed ratio.
To solve this problem, we can iterate through all possible substrings of the input string and check if the ratio of 0's to 1's in each substring matches the fixed ratio. We can keep track of the count of valid substrings and return it as the result. :
Solutions
class Solution {
public int countSubstrings(String s, int ratio) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
int zeros = 0, ones = 0;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) == '0') {
zeros++;
} else {
ones++;
}
if (zeros != 0 && ones != 0 && zeros * ratio == ones) {
count++;
}
}
}
return count;
}
}
Loading editor...