Checking if two strings are permutations of each other

前端 未结 30 1082
感情败类
感情败类 2020-12-05 08:19

How to determine if two strings are permutations of each other

30条回答
  •  天涯浪人
    2020-12-05 09:12

    I'm working on a Java library that should simplify your task. You can re-implement this algorithm using only two method calls:

    boolean arePermutationsOfSameString(String s1, String s2) {
        s1 = $(s1).sort().join(); 
        s2 = $(s2).sort().join();
        return s1.equals(s2);
    }
    

    testcase

    @Test
    public void stringPermutationCheck() {
        // true cases
        assertThat(arePermutationsOfSameString("abc", "acb"), is(true));
        assertThat(arePermutationsOfSameString("bac", "bca"), is(true));
        assertThat(arePermutationsOfSameString("cab", "cba"), is(true));
    
        // false cases
        assertThat(arePermutationsOfSameString("cab", "acba"), is(false));
        assertThat(arePermutationsOfSameString("cab", "acbb"), is(false));
    
        // corner cases
        assertThat(arePermutationsOfSameString("", ""), is(true));
        assertThat(arePermutationsOfSameString("", null), is(true));
        assertThat(arePermutationsOfSameString(null, ""), is(true));
        assertThat(arePermutationsOfSameString(null, null), is(true));
    }
    

    PS

    In the case you can clone the souces at bitbucket.

提交回复
热议问题