简体   繁体   English

在Core Java中使用递归机制在另一个字符串中查找字符串

[英]Finding a String in another String Using Recursion Mechanism in Core Java

I have the below Problem Statement 我有以下问题陈述

PS: Given a string "str" and a Non-Empty substring "sub" ,compute "Recursively" if at least "N" copies of "sub" appear in the "string somewhere", possibly with "Overlapping". PS:给定字符串“ str”和非空子字符串“ sub”,如果“ sub”的至少“ N”个副本出现在“某处的字符串”中,则可能计算“递归”,可能带有“重叠”。 N will be non-negative. N将为非负数。

Example are as shown below
strCopies("catcowcat", "cat", 2) → true
strCopies("catcowcat", "cow", 2) → false
strCopies("catcowcat", "cow", 1) → true
strCopies("iiijjj", "ii", 2) → true

I have written the code as shown below(without recursion) and is working fine for few test cases,except for others which are marked as FAIL. 我已经编写了如下所示的代码(没有递归),并且对于少数测试用例工作正常,除了其他标记为“失败”的用例。

:::Code is as shown below::: :::代码如下所示:::

public boolean strCopies(String str, String sub, int n) {    
    int len = sub.length();    
    int result=0;    
    if(len>0){    
       int start = str.indexOf(sub);    
       while(start !=-1){    
              result++;    
              start = str.indexOf(sub,start+len);                     
       }
    }          
   if(result==n){
        return true;
   }else return false; 
}

Runs for above code as shown below(Marked in BOLD are FAILED TEST CASES) 运行上述代码,如下所示(粗体标记为失败的测试案例)

Expected This Run
strCopies("catcowcat", "cat", 2) → true true OK
strCopies("catcowcat", "cow", 2) → false false OK
strCopies("catcowcat", "cow", 1) → true true OK
strCopies("iiijjj", "ii", 2) → true false FAIL
strCopies("iiiiij", "iii", 3) → true false FAIL
strCopies("ijiiiiij", "iiii", 2) → true false FAIL

Could you check and let me know what is wrong with the code for FAIL TEST CASES ?Im unable to consider the Overlapping scenarios. 您能否检查一下并让我知道FAIL TEST CASES的代码出了什么问题?我无法考虑“重叠”情况。

Well, your first problem is that your method isn't recursive. 好吧,您的第一个问题是您的方法不是递归的。 I suspect you want to work with substring as well as indexOf ... 我怀疑您想使用substring以及indexOf ...

As for why your current method isn't working, I suspect it's because you're using start + len instead of start + 1 to find the next starting position. 至于为什么您当前的方法不起作用,我怀疑是因为您使用的是start + len而不是start + 1来查找下一个起始位置。 So when trying to find "ii" in "iii", you should first look at position 0, then position 1 - currently you're looking at position 2, which would mean it wouldn't find the second "ii" starting at 1. 因此,当尝试在“ iii”中查找“ ii”时,您应该首先查看位置0,然后查看位置1-当前您正在查看位置2,这意味着它将找不到从1开始的第二个“ ii” 。

First of all, your solution is not recursive ( strCopies does not call itself). 首先,您的解决方案不是递归的( strCopies不会自行调用)。

Here is a suggestion for a recursive version of your algorithm: 这是您算法的递归版本的建议:

public static boolean strCopies(String str, String sub, int n) {
    if (str.isEmpty())
        return n == 0;
    int remainingN = str.startsWith(sub) ? n - 1 : n;
    return strCopies(str.substring(1), sub, remainingN);
}

(All your test-cases pass.) (您所有的测试用例都通过了。)


Btw, note that your last lines of code: 顺便说一句,请注意您的最后几行代码:

if(result==n)
    return true;
else
    return false; 

can always be replaced with simply 总是可以简单地替换

return result == n;
public class StackOverflow {

 public static void main(String[] args) {
  String string = "catcowcat";
  String substring = "cat";
  System.out.println(string + " has " + findNumberOfStrings(string, substring, 0) + " " + substring);
 }

 private static int findNumberOfStrings(String string, String substring, int count){
  if (string.length() == 0){
   return count + 0;
  }
  if (string.length() < substring.length()){
   return count + 0;
  }
  if (string.contains(substring)){
   count++;
   string = string.replaceFirst(substring, "");
   return findNumberOfStrings(string, substring, count);
  }
  return count;
 }

}

The pure recursion code for the problem is: 该问题的纯递归代码为:

public boolean strCopies(String str, String sub, int n) {
   if(n==0) return true;
   if(str.length()==0) return false;
   if(str.length()<sub.length()) return false;
   if(str.startsWith(sub)) return strCount(str.substring(1),sub, n, 1);
   return strCopies(str.substring(1),sub,n);
}

public boolean strCount(String str , String sub , int n , int count ) {
   if( count>= n) return true;
   if(str.length()==0) return false;
   if(str.length()<sub.length()) return false;
   if(str.startsWith(sub)) {
   count++;
   if( count>= n) return true;
   }
   return strCount(str.substring(1),sub, n , count );
}

We have to maintain a count of occurrences of sub in str string. 我们必须维护str字符串中出现sub的次数。 But in recursive call of strCopies function if we take count variable, everytime function is called the value of var count will reinitialize (we cannot maintain count in memory of function and cannot keep on adding to its previous value). 但是在递归调用strCopies函数时,如果我们使用count变量,则每次调用该函数时,var count的值都会重新初始化(我们无法将count保留在函数的内存中并且无法继续添加至其先前的值)。 So for maintaining the value of count we pass the value of count to another function strCount (as return strCount(str.substring(1), sub, n, count ) ) which also works recursively and can do count++, as it is called with a value of count only and count doesnot get reintialized rather get carried forward. 因此,为了保持count的值,我们将count的值传递给另一个函数strCount(作为return strCount(str.substring(1), sub, n, count ) ) ,该return strCount(str.substring(1), sub, n, count ) )也可以递归工作并且可以执行count ++,因为它被称为仅count的值,count不会重新初始化,而是结转。

The basic idea is that you search for the index of the sub word and then you send the new string which is starting one character after the index you have found the word since you allow overlapping. 基本思想是搜索子词的索引,然后发送新字符串,该字符串从找到该词的索引后开始一个字符,因为允许重叠。

public boolean strCopies(String str, String sub, int n) {

 if (str == null || str.equals("") || str.length() < sub.length())
  if (n == 0)
    return true;
  else 
    return false;


 int index =  str.indexOf(sub);
 if (index != -1)
  return false || strCopies(str.substring(index + 1),sub,--n);
 else
  return false || strCopies("",sub,n);

}

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

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