StringTrain
SRM 161 · 2003-08-28 · by brett1479
Problem Statement
- Train is initialized to the value of the 0th element of cars
- For each element of cars in order, beginning with element 1, check if some proper prefix of the current element matches some proper suffix of the Train. If so, append the element of cars to the Train, not repeating the matched prefix. If more than one proper prefix matches, take the longest. If no proper prefix matches, the current element of cars is not appended.
Once you have built the Train, remove all but the last occurrence of each character in the Train. For example, if the Train was (quotes for clarity) "abbbcabdb" you would be left with "cadb". You will return a string of the form "n x" where, n is the length of the Train before removing all but the last occurrence of each character, and x is the string after the removal. n and x are separated by exactly one space, the return should not have any leading or trailing whitespace, and n should have no leading zeros.
Constraints
- cars will contain between 2 and 50 elements inclusive
- Each element of cars will contain between 1 and 50 uppercase letters inclusive
{"ABCDE","CDFFF","CDE","CDEGG","GABC"}
Returns: "10 DEGABC"
The Train begins as (quotes for clarity) "ABCDE". Element 1 of cars cannot be added since it doesn't match any suffix of the Train. Element 2 of cars cannot be added since the only matching prefix is the entire string. Element 3 can be added, and the resulting Train is "ABCDEGG". Element 4 can also be added, and the resulting Train is "ABCDEGGABC". After removing all but the last occurrence of each character we are left with "DEGABC".
{"AAAAA","AAAAA","AAAAA"}
Returns: "7 A"
The Train begins as "AAAAA". The longest matching proper prefix of element 1 of cars is "AAAA" so the resulting Train is "AAAAAA". The longest matching proper prefix of element 1 of cars is "AAAA" so the resulting Train is "AAAAAAA". After removing all but the last occurrence of each character, the result is "A".
{"CABABDABAB","CABAB","ABABDABAB","DABAB"}
Returns: "15 CDAB"
{"ABABAB","ABABAB","ABABABAB","BZZZZZ"}
Returns: "15 ABZ"
{"A","A","A","AA"}
Returns: "1 A"
Submissions are judged against all 85 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class StringTrain with a public method string buildTrain(vector<string> cars) · 85 test cases · 2 s / 256 MB per case