Checking if two strings are permutations of each other in Python

前端 未结 22 2294
旧时难觅i
旧时难觅i 2020-12-08 16:04

I\'m checking if two strings a and b are permutations of each other, and I\'m wondering what the ideal way to do this is in Python. From the Zen of

22条回答
  •  囚心锁ツ
    2020-12-08 16:18

    Sorry that my code is not in Python, I have never used it, but I am sure this can be easily translated into python. I believe this is faster than all the other examples already posted. It is also O(n), but stops as soon as possible:

    public boolean isPermutation(String a, String b) {
        if (a.length() != b.length()) {
            return false;
        }
    
        int[] charCount = new int[256];
        for (int i = 0; i < a.length(); ++i) {
            ++charCount[a.charAt(i)];
        }
    
        for (int i = 0; i < b.length(); ++i) {
            if (--charCount[b.charAt(i)] < 0) {
                return false;
            }
        }
        return true;
    }
    

    First I don't use a dictionary but an array of size 256 for all the characters. Accessing the index should be much faster. Then when the second string is iterated, I immediately return false when the count gets below 0. When the second loop has finished, you can be sure that the strings are a permutation, because the strings have equal length and no character was used more often in b compared to a.

提交回复
热议问题