Ser Pounce
Ser Pounce

Reputation: 14527

Elegant Algorithm for Storing Words in a String

I have an app where the user enters text into a custom text area. If the user taps the text area, it will move the cursor to the point they just tapped, thus enabling them to insert / delete text anywhere in the text area. Restrictions being there can't be a space at the beginning of the text area, and there can't be consecutive spaces at any point in the text area (also there is no return key to create a new line). The text in the text area is stored in an attributed string called "text".

What I need to develop is an efficient algorithm that keeps track of the widest word in the text area. When I say widest, I'm not referring to character width, but the actual pixel width which I'm calculating by storing the text in a CTFrameRef and getting its size.

I've come up with a lot of brute force ways that this can be accomplished but I'm wondering if anyone knows what would be the most efficient way for both time and space to accomplish this? I obviously need some kind of data structure that keeps track of each word and its length, and I've thought of storing all the words in an array and updating them as text is inserted or deleted, but wondering if anyone can think of anything more optimal?

Upvotes: 4

Views: 184

Answers (1)

rici
rici

Reputation: 241701

You could do this with a min-heap, if you can find (or write) one which includes the modify-key operation. You'll need both increase-key and decrease-key but the good news is that both are implementable in O(log N).

Upvotes: 1

Related Questions