If I did not understand it, this problem is definitely in P.
Naive approach:
- Take all the lines in B ending with the same character as s. Name this new package B '. Can be done in O (| B |)
- , s B '. O (| B '| * max (| z |)) z B. , s z, O (| z |)
- ( O (| B '|))
| x | x.
, O (| B | * max (| z |)) .