接受兩個單詞後,利用遞歸確定第一個單詞的字母是否包含在第二個單詞的任意順序中。使用遞歸比較字符串中包含的字母?
我們只能使用.charAt字符串方法,而且.contains也是不允許的。
我在考慮從第一個單詞的第一個字符開始,看它是否等於第二個單詞-1的長度charAt,然後返回一個長度爲-1的子字符串,但這不能正常工作。
public static boolean containedWordsCheck(String firstWord,String secondWord) {
//Recursion
if (firstWord.charAt(0) == secondWord.charAt(secondWord.length()-1))
return containedWordsCheck(firstWord.substring(1, firstWord.length()-1),secondWord.substring(1, secondWord.length() - 1));
//If it reaches this far it means the letters in the first string aren't contained in the second string
return false;
如果第一個單詞是「apple」,那麼在第二個單詞中是否必須有兩個p? – ajb
如果第二個單詞中的字符可以是任意順序**,那麼您的邏輯將失敗,因爲您將第一個單詞中的第一個字符與第二個單詞中的_last_字符進行比較,而不是第二個單詞中的任何其他字符第二個字。 「以任何順序」意味着角色可以在第二個單詞中的任何地方,對嗎?你的邏輯還有其他的錯誤,但你仍然需要制定一個更好的計劃。 – ajb
你已經學過循環了嗎? – user3707125