简体   繁体   English

检查一个字符串是否与其他两个字符串交织

[英]checking if a string is interleaving of two other strings

I came across multiple links to the solution of the problem - "How to check if a string is interleaving of two other strings" 我遇到了指向该问题的解决方案的多个链接-“如何检查一个字符串是否与其他两个字符串交错”

Two solutions looked particularly interesting to me which work but I have doubts in both of them. 对于我来说,两种解决方案看起来特别有用,但我对它们都感到怀疑。

FIRST I did not get the hashing part in this where author is saying "A pure recursive solution will cause time limit exceed. We can optimize it by caching the false visited solutions in the visited set. That will short circuit many repeated search path" 首先,我没有得到哈希部分,在那儿作者说:“纯递归解决方案将导致时间限制超出。我们可以通过在访问集中缓存错误的访问解决方案来对其进行优化。这将使许多重复的搜索路径短路”

SECOND I did not the the "else condition" on line 18 in recursive. 第二,我没有递归执行第18行的“其他条件”。 Won't one of the conditions (line 14th and line 16th) will always be true as they are inside else of line 11th if condition which is if(s2.charAt(0) != s3.charAt(0) && s1.charAt(0) != s3.charAt(0)) { 如果条件为if(s2.charAt(0) != s3.charAt(0) && s1.charAt(0) != s3.charAt(0)) { ,则条件之一(第14行和第16行)将始终为真,因为它们位于第11行的其他行内if(s2.charAt(0) != s3.charAt(0) && s1.charAt(0) != s3.charAt(0)) {

First 第一

This is actually space-time tradeoff (the computation time can be reduced at the cost of increased memory use). 这实际上是时空的权衡(可以以增加内存使用为代价来减少计算时间)。 Why does the author say pure recursive solution slow (in fact it's exponential time complexity)? 为什么作者说纯递归解决方案比较慢(实际上是指数时间复杂度)? It comes from repeated recursion and because of that, it computes the same values again and again. 它来自重复的递归,因此,它一次又一次地计算相同的值。

So what can you do? 所以,你可以做什么? You can store the value you already computed. 您可以存储您已经计算的值。 Next time you want this value again, just look up in a table. 下次您再次想要该值时,只需在表中查找即可。 This is called caching, when the values are cached, you can treat every recursive call inside the function as it would run in O(1) time complexity. 这称为缓存,当缓存值时,您可以将函数内的每个递归调用都视为O(1)时间复杂性来处理。 The core idea is don't calculate the same things twice. 核心思想是不要两次计算相同的事物。

Second 第二

In the case s2.charAt(0) == s3.charAt(0) && s1.charAt(0) == s3.charAt(0) . s2.charAt(0) == s3.charAt(0) && s1.charAt(0) == s3.charAt(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM