#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "math.h"
int GetMaxSubLen(char *d, int dSize, int maxCost)
{
int left = 0;
int right = 0;
int len = 0;
int sum = 0;
while(right < dSize) {
sum += d[right];
right++;
if (sum <= maxCost) {
len = len > (right - left) ? len : (right - left);
}
while (sum > maxCost) {
sum -= d[left];
left++;
}
}
len = len > (right - left) ? len : (right - left);
return len;
}
int equalSubstring(char * s, char * t, int maxCost){
int maxLen = 0;
if ((s == NULL) || (t == NULL)) {
return maxLen;
}
int lenS = strlen(s);
int lenT = strlen(t);
if (lenS != lenT) {
return maxLen;
}
char *d = (char *) malloc(lenS + 1);
(void)memset(d, 0, lenS + 1);
for (int i = 0; i < lenS; i++) {
d[i] = s[i] > t[i] ? (s[i] - t[i]) : (t[i] - s[i]);
// printf("d[%d] [%d]\n", i, d[i]);
}
maxLen = GetMaxSubLen(d, lenS, maxCost);
return maxLen;
}
void TestCase01()
{
char s[] = "abcd";
char t[] = "bcdf";
int maxCost = 3;
int maxLen = equalSubstring(s, t, maxCost);
printf("maxLen %d\n", maxLen);
}
void TestCase02()
{
char s[] = "abcd";
char t[] = "cdef";
int maxCost = 3;
int maxLen = equalSubstring(s, t, maxCost);
printf("maxLen %d\n", maxLen);
}
void TestCase03()
{
char s[] = "abcd";
char t[] = "acde";
int maxCost = 0;
int maxLen = equalSubstring(s, t, maxCost);
printf("maxLen %d\n", maxLen);
}
int main ()
{
TestCase01(); // 3
TestCase02(); // 1
TestCase03(); // 1
// printf("-----Life is short, do somthing meaningful!\n");
system("pause");
system("cls");
return 0;
}