Generation

generate functionTue, 18 Jul 2023

There is a list A made of N strings, each of length 2. Two strings can be connected together if the letter ending the first string is the same as the letter beginning the second string. For example, the two strings "ab" and "bc" can be connected, as "ab" ends with a "b" character and "ba" begins with a "b" character. Potentially more strings can be connected to form a longer chain if the last letter of the previous string is the same as the first letter of the next string, e.g. "ab"-"ba"- "ac"-"cb". For every k from 0 to N-1, check if string A[0],... A[k] can be connected together or not. Strings can be reordered but not reversed.Write a function: string solution(vector<string> &A); that, given an array A consisting of N strings, each of length 2, returns a string of length N. The K-th character of the string should be '1' if strings A[0],..., A[K] can be connected into a single string, or 'O' otherwise.

#include <algorithm> #include <vector> #include <string> string solution(vector<string> &A) { string result = ""; for (int i = 0; i < A.size(); i++) { if (i == A.size() - 1) { result += "1"; break; } result += "0"; string last = A[i].substr(1); string first = A[i+1].substr(0, 1); if (last == first) { result[i] = "1"; } } return result; }

Want to kickstart your project?Use the new AI Studio to create your code