How to Solve Morse Code Problem in Practice

Problem Link
My Solution (TLE)
Hello Programmers , While solving this question i got a TLE as there is no Editorial available , and strict time limits i am stuck, Anyone have any optimal approach ? Thank You