我被困在这个面试问题上。 给出一个单词 S 和一个字符串数组 A 。如何找到可形成S的A元素的所有可能组合 例如:
S = "hotday"
A = ["o","ho","h","tday"]
可能的组合是:(" h" +" o" +" tday")和(" ho" +&#34 ; tday"。)
感谢
答案 0 :(得分:4)
您可以使用回溯。这是一些伪代码:
def generateSolutions(unusedWords, usedWords, string, position):
if position == string.length():
print(usedWords)
else:
for word in unusedWords:
if word is a prefix of string[position ... s.length() - 1]:
generateSolutions(unusedWords - word, usedWords + word,
string, position + word.length())
generateSolution(words, an empty list, input string, 0)
这个想法非常简单:我们可以选择一个与输入字符串其余部分的前缀相匹配的未使用的单词,并继续递归生成所有有效的组合(我假设我们只能使用给定单词列表中的每个单词)一旦)。该解决方案具有指数时间复杂度,但在最坏的情况下不可能做得更好。例如,如果给定字符串为abcdef...yz
且单词列表为[a, b, c, ..., z, ab, cd, ..., yz]
,则此类组合的数量为2 ^ n / 2
,其中n
是给定字符串的长度
答案 1 :(得分:2)
您可以遍历A的所有排列并查看哪些排列合适。 Python示例实现:
import itertools
S = "hotday"
A = ["o","ho","h","tday"]
for count in range(len(A)):
for pieces in itertools.permutations(A, count):
if "".join(pieces) == S:
print pieces
结果:
('ho', 'tday')
('h', 'o', 'tday')
是的,这是O(N!),但对于你提供的小A
来说这很好。
答案 2 :(得分:0)
这是我的java解决方案,它是" ILoveCoding"的伪代码的实现。 :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class PossibleCombination {
public static void printPossibleCombinations(String[] tab, String S)
{
ArrayList<String> used = new ArrayList<String>();
ArrayList<String> notused = new ArrayList<String>(Arrays.asList(tab));
printPossibleCombinations(used, notused, S,0);
}
private static void printPossibleCombinations(ArrayList<String> used,
ArrayList<String> notused, String s,int pos) {
if (pos == s.length())
{ System.out.println("Possible combinaiton : ");
for(String e : used)
{
System.out.print(e + " - ");
System.out.println();
}
}
HashSet<String> prefixes = getPossiblePrefixes(s,pos);
for(String e : notused)
{
if (prefixes.contains(e))
{
ArrayList<String> isused = new ArrayList<String>(used);
isused.add(e);
ArrayList<String> isnotused = new ArrayList<String>(notused);
isnotused.remove(e);
printPossibleCombinations(isused, isnotused,s, pos + e.length());
}
}
}
private static HashSet<String> getPossiblePrefixes(String s, int pos) {
HashSet<String> prefixes = new HashSet<String>();
for(int i = pos ; i<= s.length() ; i++)
{
prefixes.add(s.substring(pos,i));
}
return prefixes;
}
public static void main(String[] args) {
String[] tab = {"o","ho","h","tday"};
String S = "hotday";
printPossibleCombinations(tab, S);
}
}