Checking if two strings are permutations of each other

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

How to determine if two strings are permutations of each other

30条回答
  •  鱼传尺愫
    2020-12-05 09:10

    Here is a simple program I wrote that gives the answer in O(n) for time complexity and O(1) for space complexity. It works by mapping every character to a prime number and then multiplying together all of the characters in the string's prime mappings together. If the two strings are permutations then they should have the same unique characters each with the same number of occurrences.

    Here is some sample code that accomplishes this:

    // maps keys to a corresponding unique prime
    static Map primes = generatePrimes(255); // use 255 for
                                                                // ASCII or the
                                                                // number of
                                                                // possible
                                                                // characters
    
    public static boolean permutations(String s1, String s2) {
        // both strings must be same length
        if (s1.length() != s2.length())
            return false;
    
        // the corresponding primes for every char in both strings are multiplied together
        int s1Product = 1;
        int s2Product = 1;
    
        for (char c : s1.toCharArray())
            s1Product *= primes.get((int) c);
    
        for (char c : s2.toCharArray())
            s2Product *= primes.get((int) c);
    
        return s1Product == s2Product;
    
    }
    
    private static Map generatePrimes(int n) {
    
        Map primes = new HashMap();
    
        primes.put(0, 2);
    
        for (int i = 2; primes.size() < n; i++) {
            boolean divisible = false;
    
            for (int v : primes.values()) {
                if (i % v == 0) {
                    divisible = true;
                    break;
                }
            }
    
            if (!divisible) {
                primes.put(primes.size(), i);
                System.out.println(i + " ");
            }
        }
    
        return primes;
    
    }
    

提交回复
热议问题