Given N strings. Each string contains only lowercase letters from a−j
(both inclusive). The set of N strings is said to be GOOD SET if no string is prefix of another string else, it is BAD SET.
For example, aab
, abcde
, aabcd
is BAD SET because aab
is prefix of aabcd
.
Print GOOD SET if it satisfies the problem requirement. Else, print BAD SET and the first string for which the condition fails.
Input Format:
First line contains N, the number of strings in the set.
Then next N lines follow, where ith line contains ith string.
Constraints:
1 ≤ N ≤ 105
1 ≤ Length of the string ≤60
Output Format:
Output GOOD SET if the set is valid.
Else, output BAD SET followed by the first string for which the condition fails.
Can anyone suggest on this?
答案 0 :(得分:0)
构造一个trie,将每个字符串逐个插入到trie中,记录指向表示插入trie中的每个字符串的节点的指针。完成后,扫描节点指针以查找所有字符串。如果其中任何一个在内部节点结束,那么它就是BAD SET。否则,(所有字符串在不同的叶子上结束),它是一个好的集合。时间和空间复杂度都与所有字符串的总长度成线性关系。