这是一道面试题。假设您有一个字符串text
和一个dictionary
(一组字符串)。如何将text
分解为子字符串,使得每个子字符串都在dictionary
中找到。
例如,您可以使用/usr/share/dict/words
将"thisisatext"
分解为["this", "is", "a", "text"]
。
我认为回溯法可以解决这个问题(伪Java代码):
void solve(String s, Set<String> dict, List<String> solution) { if (s.length == 0) return for each prefix of s found in dict solve(s without prefix, dict, solution + prefix) }
List<String> solution = new List<String>() solve(text, dict, solution)
这个算法有意义吗?您会优化在字典中搜索前缀的步骤吗?您会推荐哪些数据结构?