I'm trying to find a way to determine all possible words that can be spelled out by a given number, given a mapping of alphabets to values.
I eventually want to find a solution that works for any 1- or 2- digit value mapping for a letter, but for illustration, assume A=1, B=2, ... Z=26.
Example: 12322
can be equal to abcbb (1,2,3,2,2)
, lcbb (12,3,2,2)
, awbb (1,23,2,2)
, abcv (1,2,3,22)
, awv (1,23,22)
, or lcv (12,3,22)
.
Here's what I have thought of so far:
I will build a tree of all possible words using the number.
To do this, I will start out with a tree with one root node with dummy data.
I will parse then the number digit-by-digit starting from the least significant digit.
At each step, I will take the last digit of the remaining part of the number and insert it into the left subtree of the current node, and remove that digit from the number for that node's left subtree. For the same node, I will then check if the previous TWO digits together form a valid alphabet, and if so, I will put them into the right subtree (and remove the 2 digits from the number for that node's right subtree).
I will then repeat the above steps recursively for each node, using the part of the number that's left, until there are no more digits left.
To illustrate, for 12322
my tree will look something like this:
*
/ \
/ \
2 22
/ / \
2 3 23
/ \ / \ /
3 23 2 12 1
/ \ / /
2 12 1 1
/
1
To get the words then, I will traverse all possible paths from the leaves to the nodes.
This seems to be an overly complex solution for what I thought would be a fairly simple problem, and I'm trying to find if there's a simpler way to solve this.