Task:
Several lines are read from the input stream. The first line contains the number
N
- the number of remaining lines (tests),N < 32
. Each of the nextN
lines contains two words separated by a space. (The length of each word does not exceed 32). It is necessary to get a new word for each pair of words, so that the ending of the first one coincides with the beginning of the second one, for example,mountain
+insane
=mountainsane
. This word should be output to the standard output stream. If it is possible to connect words in several ways, you should choose the one that provides the maximum common part, e.g.papa
+papaha
=papaha
(notpapapapaha
).Note: it is unacceptable to output the final string character by character using the
"%c"
format. It is necessary to form and output the whole string using the"%s"
format.
This is my code:
#include <stdio.h>
#include <string.h>
int word_length(char *str)
{
unsigned short int i;
for (i = 0; str[i] != '\0'; i++);
return i;
}
int main() {
char word_1[32], word_2[32], line[64][64];
unsigned short int n, line_number, i, j, k;
scanf("%hu", &n);
for (line_number = 0; line_number < n; line_number++) {
scanf("%s %s", word_1, word_2);
if (word_2[0] == word_1[0] && word_2[1] == word_1[1]) {
for (i = 0; i < word_length(word_2); i++) {
line[line_number][i] = word_2[i];
}
} else {
for (j = 0; j < word_length(word_1); j++) {
if (word_2[0] != word_1[j]) {
line[line_number][j] = word_1[j];
} else {
line[line_number][j] = word_2[j];
break;
}
}
for (k = j; k <= word_length(word_2); k++) {
line[line_number][k] = word_2[k - 1];
}
}
}
printf("\n");
for (line_number = 0; line_number < n; line_number++) {
printf("%s\n", line[line_number]);
}
return 0;
}
The basic idea is to go by the first word and look for a match with the first letter of the second word. If the letters are different, then the letter from word 1 is written down, if they match, then all letters from word 2 are written down. However, I'm not sure if this logic is correct.
Try | Expect | Got |
---|---|---|
papa mama | papamama | papaa |
mountain insane | mountainsane | mountae |
play yoga | playoga | plaga |
papa papaha | papaha | papaha |
In the end I came up with this program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* mergeWords(char* word1, char* word2) {
int len1 = strlen(word1);
int len2 = strlen(word2);
int maxSize = len1 + len2 + 1;
char* merged = (char*)malloc(maxSize * sizeof(char));
int commonLen = 0;
for (int i = 0; i < len1; i++) {
int match = 1;
for (int j = 0; j < len1 - i; j++) {
if (word1[i + j] != word2[j]) {
match = 0;
break;
}
}
if (match) {
commonLen = len1 - i;
break;
}
}
strncpy(merged, word1, len1 - commonLen);
merged[len1 - commonLen] = '\0';
strcat(merged, word2);
return merged;
}
int main() {
int n;
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++) {
char word1[33], word2[33];
scanf("%s %s", word1, word2);
getchar();
char* merged = mergeWords(word1, word2);
printf("%s\n", merged);
free(merged);
}
return 0;
}