找到有效的字符串组合给出一个数的最大数量 [英] Find the maximum number of valid string combinations given a number

查看:171
本文介绍了找到有效的字符串组合给出一个数的最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于一个HashMap,其中的映射是:

Given a HashMap where the mapping is:

a => 1
b => 2
...
...
z => 26

查找可从该号码产生串的最大数。例如:

Find the maximum number of strings that could be generated from that number. For example:

function("111") = 3
// aaa - 1,1,1
// ak - 1, 11
// ka - 11, 1

function("26") = 2
// bf - 2, 6
// z - 26

function("101") = 1
// ja - 10, 1
// note that there are no other possibilities since 0 does not map to anything

这将是有益的,如果有人能提供解决方案,code在Java中。谢谢!

It would be helpful if someone could provide the solution code in Java. Thanks!

推荐答案

我在一些采访中这个问题,当我没有使用伪code,或只是在黑板上画它回答这个问题,面试官很IM pressed。

I had this question in some interview, when I did answer the question using pseudo code or just drawing it on the board, the interviewer was very impressed.

我没有确切的解决方案,但是因为它太复杂,它最好不要被实现为递归。

I don't have the exact solution, but it better not be implemented as a recursion because it's too complicated.

解决方法:
我们的想法是让所有可能的组合,可以通过字符串长度的函数参数做出的。
比方说,你输入的是111,这样可能的组合有:

SOLUTION:
The idea is to have all the possible combinations that you can make of by the String length which is the function parameter.
Let's say that your input is "111" so the possible combinations are:

  • 在1,1,1
  • 11,1
  • 1,11

每当我们需要的一个两个从字符串参数正确的地方? 这听起来像二进制的,所以我们可以标记:

Each time we need to take one or two places from the String parameter right? It sounds like binary, so we can mark:

  • 一个作为0
  • 两个作为1
  • one as '0'
  • two as '1'

因此​​,我们的组合以上是这样的:

So our combinations above are like:

  1. 在1,1,1 == >> 0,0,0
  2. 11,1 == >> 1,0
  3. 1,11 == >> 0,1

通过每个二进制组合,我们可以从字符串值,并找到我们从ABC需要的字母。如果某些值不能在1-26的范围内发现,所以它不是有效的。

By each binary combination we can take values from the string and find the letters we need from the ABC. If some value can't be found in range of 1-26 so it's not valid.

将溶液从一个计算开始如何找到可能的组合由String长度作为参数

The solution starts from a calculation how to find the possible combinations by the String length as given as a parameter.

这篇关于找到有效的字符串组合给出一个数的最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆