A string S is passed as the input. Two words W1 and W2 which are present in the string S are also passed as the input. The program must find the minimum distance D between W1 and W2 in S (in forward or reverse order) and print D as the output.
#include <stdio.h>
#include <string.h>
// Function to find minimum distance between two words in a string
int findMinDistance(char str, char word1, char *word2) {
int len = strlen(str);
int minDistance = len; // Initialize to a large value
// Iterate through the string
for (int i = 0; i < len; i++) {
int currentDistance = 0;
// Check for the occurrence of the first word
if (strncmp(str + i, word1, strlen(word1)) == 0) {
// Calculate the distance between the two words
for (int j = i + strlen(word1); j < len; j++) {
currentDistance++;
// Check for the occurrence of the second word
if (strncmp(str + j, word2, strlen(word2)) == 0) {
if (currentDistance < minDistance) {
minDistance = currentDistance;
}
break;
}
}
}
// Check for the occurrence of the second word
if (strncmp(str + i, word2, strlen(word2)) == 0) {
// Calculate the distance between the two words
for (int j = i + strlen(word2); j < len; j++) {
currentDistance++;
// Check for the occurrence of the first word
if (strncmp(str + j, word1, strlen(word1)) == 0) {
if (currentDistance < minDistance) {
minDistance = currentDistance;
}
break;
}
}
}
}
return minDistance;
}
// Main function
int main() {
char str[1000], word1[100], word2[100];
// Input string and two words
scanf("%s %s %s", str, word1, word2);
// Find and print the minimum distance
printf("%d", findMinDistance(str, word1, word2));
return 0;
}
Explanation:
findMinDistance
is a function that takes a stringstr
and two wordsword1
andword2
as input and returns the minimum distance between the occurrences ofword1
andword2
in the string.The function initializes
minDistance
to the length of the string, representing an initially large distance.It then iterates through the string using a loop.
Inside the loop, it checks for the occurrence of
word1
andword2
at the current position in the string.If
word1
is found, it calculates the distance to the next occurrence ofword2
.If
word2
is found, it calculates the distance to the next occurrence ofword1
.It updates
minDistance
if the calculated distance is smaller than the currentminDistance
.The main function takes input for the string
str
and the two wordsword1
andword2
.It then calls the
findMinDistance
function and prints the result.