Programmer Interview Golden Classic-Interview Question 01.02. Determine whether they are character rearrangements

1. Topic introduction

Given two strings s1 and s2, please write a program to determine whether the characters of one string can be changed into another string after rearranging the characters.

Example 1:

Input: s1 = "abc", s2 = "bca"
Output: true 
Example 2:

Input: s1 = "abc", s2 = "bad"
Output: false
Description:

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

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-permutation-lcci The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       Use the characteristic of ^ (exclusive OR) operation, that is, the same is 0, and the difference is 1. The elements in the two strings are XORed sequentially. If it is 0, it proves that the elements in the two strings are the same, that is, one string s2 can become another string s2 after being rearranged. See the code for details.

Three, problem-solving code

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if(s1.size() != s2.size())
            return false;
        int ret = 0;
        for(int i = 0; i < s1.size(); ++i)
        {
            ret ^= s1[i] ^ s2[i];
        }
        return ret == 0 ? true:false;
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/105574178