Whether the leetcode determines whether the characters are rearranged



This article mainly records whether the determination of leetcode is mutual character rearrangement


Given two strings s1 and s2, write a program that determines whether one string can be rearranged into another string by rearranging the characters.

Example 1:

Input: s1 = "abc", s2 = "bca"
output: true 

Example 2:

Input: s1 = "abc", s2 = "bad"
output: false


    0 <= len(s1) <= 100
    0 <= len(s2) <= 100 

Source: LeetCode
Link: https://leetcode-cn.com/problems/check-permutation-lcci
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.


class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if(s1.length() != s2.length()) {
            return false;
        int len = 'z' + 1;
        int[] idx1 = new int[len];
        int[] idx2 = new int[len];
        for(int i=0; i<s1.length(); i++){
            idx1[s1.charAt(i)] = idx1[s1.charAt(i)] + 1;
            idx2[s2.charAt(i)] = idx2[s2.charAt(i)] + 1;

        for(int i=0; i<len; i++){
            if (idx1[i] != idx2[i]) {
                return false;
        return true;


Here, the number of characters of the two strings is maintained separately, and then it is traversed to determine whether the number of each character is equal.


  • Determine whether the characters are rearranged for each other