PVP PVP - 1 year ago 58
Java Question

check if two strings are permutation of each other?

I'm solving this question as a assignment of the school.But the two of my test cases are coming out wrong when i submit the code? I don't know what went wrong. I have checked various other test cases and corner cases and it all coming out right.

Here is my code:

public static boolean isPermutation(String input1, String input2) {

if(input1.length() != input2.length())
{
return false;
}

int index1 =0;
int index2 =0;
int count=0;


while(index2<input2.length())
{

while(index1<input1.length())
{
if( input1.charAt(index1)==input2.charAt(index2) )
{
index1=0;
count++;
break;
}
index1++;

}
index2++;
}


if(count==input1.length())
{
return true;
}


return false;

}


SAMPLE INPUT

abcde
baedc


output

true


SAMPLE INPUT

abc
cbd


output

false

Answer Source

A simpler solution would be to sort the characters in both strings and compare those character arrays.

Example

public static void main(String[] args) {
    System.out.println(isPermutation("hello", "olleh"));
    System.out.println(isPermutation("hell", "leh"));
    System.out.println(isPermutation("world", "wdolr"));
}

private static boolean isPermutation(String a, String b) {
    char [] aArray = a.toCharArray();
    char [] bArray = b.toCharArray();
    Arrays.sort(aArray);
    Arrays.sort(bArray);
    return Arrays.equals(aArray, bArray);
}

A more long-winded solution without sorting would to be check every character in A is also in B

private static boolean isPermutation(String a, String b) {
    char[] aArray = a.toCharArray();
    char[] bArray = b.toCharArray();

    if (a.length() != b.length()) {
        return false;
    }
    int found = 0;
    for (int i = 0; i < aArray.length; i++) {
        char eachA = aArray[i];
        // check each character in A is found in B
        for (int k = 0; k < bArray.length; k++) {
            if (eachA == bArray[k]) {
                found++;
                bArray[k] = '\uFFFF'; // clear so we don't find again
                break;
            }
        }
    }
    return found == a.length();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download