/* Given a list of strings L and a string S, determine if S can be constructed by concatenating elements from L. Each element can be used multiple times. */ #include #include #include #include #include #include #include using namespace std; vector L; string S; void getL(); void getS(); bool ifStringMatchS(string test, string S, int cutBegin); void solve(vector L, string S); int main() { getL(); getS(); solve(L, S); return 0; } void getL() { int amountOfStrings; string temp_String; cout << "Type amount of strings in set L:" << endl; cin >> amountOfStrings; cout << "Type " << amountOfStrings << " strings followed by enter:" << endl; for (int i = 0; i < amountOfStrings; i++) { cin >> temp_String; L.push_back(temp_String); } } void getS() { cout << "Type string S:" << endl; cin >> S; } bool ifStringMatchS(string test, string S, int cutBegin) { string cuttedS = S.substr(cutBegin, test.size()); return !test.compare(cuttedS); } void solve(vector L, string S) { vector ifPossibleArray(S.size(), 0); string cuttedS; int L_ending; // go through ifPossibleArray to check if we are able to // create beginning of first chars of S string for (int i = 0; i < S.size(); i++) { // go through L array if we are able to match its // elements with beginning of S string without first // i chars for (int j = 0; j < L.size(); j++) { // where L[j] ends on ifPossibleArray with cutted // first i chars L_ending = i + L[j].size() - 1; // do not check if we are not able to get there if (i == 0 || ifPossibleArray[i - 1]) { // do not check if too long L element nor already checked if ((L_ending < S.size()) && ifPossibleArray[L_ending] == 0) { // do not update ifPossibleArray if string comaprision fails if (ifStringMatchS(L[j], S, i)) { ifPossibleArray[L_ending] = j + 1; } } } } } // print an example of sulution if (ifPossibleArray[S.size() - 1]) { cout << "solution exists:" << endl; vector printSolution; int i = S.size() - 1; do { printSolution.push_back(L[ifPossibleArray[i] - 1]); i -= L[ifPossibleArray[i] - 1].size(); } while (i != -1); cout << S << " = "; for (i = printSolution.size() - 1; i > 0; i--) { cout << printSolution[i] << " + "; } cout << printSolution[i]; } else { cout << "solution doesn't exist"; } }