user6824475
user6824475

Reputation:

Using Recursion to compare letters contained in a string?

After taking in two words, utilizing recursion to determine if the letters of the first word are contained IN ANY ORDER in the second word.

We can only utilize the .charAt string method and .contains is also not allowed.

I was thinking starting with the first character of the first word and seeing if it was equal to the charAt the length of the second word -1, then returning a substring of length -1 but this isn't working correctly.

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;

Upvotes: 0

Views: 2938

Answers (2)

Martin Polak
Martin Polak

Reputation: 124

Something like this should work. It is using helper recursive function and only charAt() as you proposed. Complexity will be O(n^2). If you do pre sort, it will be a lot easier as you can see in other answer.

public boolean containedWordsCheck(String firstWord,String secondWord) {
    if (firstWord.isEmpty()) {
        return true;
    }
    if (containChar(secondWord, firstWord.charAt(0))) {
        return true && containedWordsCheck(firstWord.substring(1, firstWord.length()), secondWord);
    } else {
        return false;
    }
}

public boolean containChar(String word, char ch) {
    if (word.isEmpty()) {
        return false;
    }
    if (word.charAt(0) == ch) {
        return true || containChar(word.substring(1, word.length()), ch);
    } else {
        return containChar(word.substring(1, word.length()), ch);
    }
}

Upvotes: 1

Karthik Bharadwaj
Karthik Bharadwaj

Reputation: 444

import java.util.Arrays;

public class FunLetters {

    public static void main(String[] args) {


        String a = "apple";
        String b = "pplea";

        char[] aArr = a.toCharArray();
        Arrays.sort(aArr);
        char[] bArr = b.toCharArray();
        Arrays.sort(bArr);
        boolean answer = checkForSameString(aArr, bArr, 0);
        System.out.println(answer);

    }


    private static boolean checkForSameString(char[] a, char[] b, int i) {

        if (i == a.length || i == b.length)
            return true;
        if (a[i] == b[i])
            return checkForSameString(a, b, i + 1);
        return false;
    }

Upvotes: 0

Related Questions