Write a program that reads a sequence of words and prints, for each word, all the other words of the sequence contained in it.
Your program has to implement and use the function
bool conte (string s1, string s2)
that returns true, if the word |s1| contains the word |s2| under the precondition that the length of |s1| is greater or equal than the length of |s2|.
Input format
Input consists in a natural number n followed by n different words p1,…,pn.
Output format
The program has to print a line for each p1,…,pn in this order. Each line starts with pi, followed by the symbol “:” and the list of all the input words contained in pi, in the same order than the input. Notice that the list corresponding to each pi always includes pi, since every word contains itself.
As usual my program works fine with the public inputs, however the privates give a wrong answer.
Public test case
INPUT 1
9
lighten
in
o
en
building
light
build
enlightenment
world
OUTPUT 1
lighten: lighten en light
in: in
o: o
en: en
building: in building build
light: light
build: build
enlightenment: lighten en light enlightenment
world: o world
INPUT 2
9
rem
pa
o
re
paraula
em
para
remor
mor
OUTPUT 2
rem: rem re em
pa: pa
o: o
re: re
paraula: pa paraula para
em: em
para: pa para
remor: rem o re em remor mor
mor: o mor
Lastly, the code. I will make a brief explanation of what this does after the code itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
#include <vector>
using namespace std;
bool conte (string s1, string s2) {
int counter = 0, i_reducer = 0;
bool increase = true;
for (int i = 0; i < s2.size(); ++i) {
for (int j = 0; j < s1.size(); ++j) {
if (s2[i] == s1[j]) {
++counter, ++i, ++i_reducer, increase = true;
if (counter == s2.size()) {
cout << " ";
return true;
}
}
else {
counter = 0;
if (increase) {
increase = false;
i -= i_reducer;
}
}
}
}
return false;
}
int main () {
int size;
cin >> size;
vector <string> s (size);
for (int i = 0; i < size; ++i) cin >> s[i];
for (int i = 0; i < size; ++i) {
cout << s[i] << ":";
for (int j = 0; j < size; ++j) {
if (s[i].size() >= s[j].size() and conte (s[i], s[j])) {
cout << s[j];
}
}
cout << endl;
}
}
|
Main function
Variables declaration
Write vector
2 loops for checking all the other strings with each string
Condition to call conte function:
s[i].size() >= s[j].size()
The condition is this one because there is no need to check if a bigger string is inside a smaller one since it is impossible. |
Conte function
Variable declaration
I use counter to see how many consecutive chars both strings share. When chars aren't equal I reset counter to 0 |
i_reducer and increase go together. They are used when the smaller string share some characters with the bigger one but it isn't inside of it. An example would be "India" "Inda" |
2 loops with each one being limited by the size of the strings