-2

I'm trying to write a boolean method that would return true if the word in the first string can be re-arranged to spell the word in the second string. So for example, ("basketball","soccer") would return false and ("basketball","baseball") would return true.

This what I got so far for my method.

public static boolean canSpell (String first, String second) {

  boolean canspell = false;

  if (first.contains(second)) {
     canspell = true;
  }
  return canspell;
}

but contains seems to only work if the two strings are exactly the same.

user1803551
  • 12,965
  • 5
  • 47
  • 74
VHTran
  • 1
  • 1
  • Focus on the letters. I will not say more than that because this is your homework. – Joe C Oct 31 '17 at 06:19
  • 1
    Your second example is inconsistent with the word "re-arrange". What you are trying to do is find if every letter in the second string is present in the first one with same number of occurrence. – kazisami Oct 31 '17 at 06:30

3 Answers3

0

Here is how can you achieve this,

  1. Remove duplicates from String first and second

Removing duplicates from a String in Java

  1. Sort Both the Strings

Sort a single String in Java

Compare both strings equals or equalIgnorecase

If you are not bothered about efficiency much , above steps are simple.

Else you can use your own hashmap or advanced data structures.

Rishabh Dugar
  • 606
  • 5
  • 16
0

What you want to check is that strings are Anagrams. contains method checks if one string is contained in the other string exactly the same. If not, it returns false. So one simple approach to solve what you are trying to do is to sort both the strings and check whether they are equal.

0

My logic: Take second string and find if each letter is in first string, remove if present. ( This is to handle the case of repeated letters also). return true if all the letters in second including repetitions are present in first string. This way the rearrangements can be taken care.

You can find the working function here:

public static boolean canSpell (String first, String second) 
    {
        //String original=first;
         boolean canspell = false;

        for(int i=0;i<second.length();i++)
        {
            char a=second.charAt(i);
            if(first.indexOf(a)>=0)
            {
                int b=first.indexOf(a);
                first = first.substring(0, b) + first.substring(b+1);
                canspell=true;
                continue;
            }
            else
            {
                canspell=false;
                break;
            }
        }
        return canspell;
    }
nionika
  • 11
  • 3