使用递归在字符串中搜索指定的子字符串

时间:2019-04-17 21:28:00

标签: java

我正在做一个简短的项目,以使用递归在字符串中搜索指定的子字符串。

我尝试使用各种字符串和子字符串,并使我的代码尽可能简单,但是如果子字符串超过一个字符,它将始终返回false。 (我有一个访问器和更改器,并且在此方法之前将int i设置为0)

public boolean find(String target) {
    if (i == target.length()) {
        return true;
    }
    System.out.println(sentence);
    if (sentence.length() < target.length()) {
        return false;
    }
    if (getSentence().toLowerCase().charAt(0) == target.toLowerCase().charAt(0)) {
        i++;
    } else {
        i = 0;
    }
    sentence = sentence.substring(1);
    return find(target);
}

测试器代码和输出:

public static void main(String[] args) {
    Sentence test = new Sentence("Lizard");
    System.out.println(test.find("z"));

    Sentence test2 = new Sentence("Seventeen");
    System.out.println(test2.find("teen"));     
}
Lizard 
izard 
zard 
true 

Seventeen 
eventeen 
venteen 
enteen 
nteen 
teen 
een 
false

1 个答案:

答案 0 :(得分:2)

您的方法仅在第一个字符处测试#python 2.7 import pandas as pd import numpy as np np.random.seed(seed=1) df = pd.DataFrame({"var1": np.random.random(100), "var2": np.random.random(100) + 5}) # Bin the data frame by "var1" with 10 bins... df = df.groupby(pd.cut(df.var1, 10)).describe().var2[['mean','count']] df =df.reset_index() print df" #Results: var1 mean count 0 (-0.000874, 0.099] 5.546257 11.0 1 (0.099, 0.198] 5.434613 12.0 2 (0.198, 0.297] 5.483686 9.0 3 (0.297, 0.396] 5.313241 6.0 4 (0.396, 0.494] 5.537168 13.0 5 (0.494, 0.593] 5.518476 10.0 6 (0.593, 0.692] 5.614630 10.0 7 (0.692, 0.791] 5.443415 10.0 8 (0.791, 0.89] 5.464804 7.0 9 (0.89, 0.989] 5.418756 12.0 ,但是您修改了target-例如您还需要在递归时修改sentence。像

target