I'm posting a solution for LeetCode's "Count Substrings That Differ by One Character". If you'd like to review, please do. Thank you!
Problem
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.
Example 1:
Example 2:
Constraints:
- 1 <= s.length, t.length <= 100
- s and t consist of lowercase English letters only.
Code
#include <stdio.h>
#include <string.h>
static const size_t getCounts(
const char *source,
const char *target,
size_t s_index,
size_t t_index
) {
size_t counter = 0;
size_t prev = 0;
size_t curr = 0;
while (s_index < strlen(source) && t_index < strlen(target)) {
++curr;
if (source[s_index] != target[t_index]) {
prev = curr;
curr = 0;
}
counter += prev;
++s_index;
++t_index;
}
return counter;
}
static const int countSubstrings(
const char *source,
const char *target
) {
size_t counters = 0;
for (size_t s_index = 0; s_index < strlen(source); ++s_index) {
counters += getCounts(source, target, s_index, 0);
}
for (size_t t_index = 1; t_index < strlen(target); ++t_index) {
counters += getCounts(source, target, 0, t_index);
}
return counters;
}
int main() {
printf ("%i \n", countSubstrings("aba", "baba"));
printf ("%i \n", countSubstrings("ab", "bb"));
printf ("%i \n", countSubstrings("a", "a"));
printf ("%i \n", countSubstrings("abe", "bbc"));
printf ("%i \n", countSubstrings("abeaskdfjpoirgfjifjwkdafjaksld",
"fqowuerflqfdjcasdjkvlfkjqheofkjsdjfasldkf"));
return 0;
}
Outputs:
6
3
0
10
1314