Checking if two strings are permutations of each other

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

How to determine if two strings are permutations of each other

30条回答
  •  Happy的楠姐
    2020-12-05 09:10

    You can try to use XOR, if one string is a permeation of the other, they should have essentially identical chars. The only difference is just the order of chars. Therefore using XOR trick can help you get rid of the order and focus only on the chars.

    public static boolean isPermutation(String s1, String s2){
        if (s1.length() != s2.length()) return false;
        int checker = 0;
        for(int i = 0; i < s1.length();i++ ){
            checker ^= s1.charAt(i) ^ s2.charAt(i);
        }
    
        return checker == 0;
    }
    

提交回复
热议问题