LeetCode interview question 01.02. Determine whether each other is a character rearrangement

Article Directory


1. Topic

  Given two strings s1 and s2 composed of lowercase letters, please write a program to determine whether the characters of one of the strings can be changed into another string after rearrangement. Click here to jump .

  Example 1:

Input: s1 = “abc”, s2 = “bca”
Output: true

  Example 2:

Input: s1 = “abc”, s2 = “bad”
Output: false

  illustrate:

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

2. C# solution

Similar to the LeetCode interview question 01.01. Determine whether a character is unique or not , use an array to record the number of occurrences. If the number of occurrences of each character is the same, the result will be the same after rearrangement.

public class Solution {
    
    
    public bool CheckPermutation(string s1, string s2) {
    
    
        int l1 = s1.Length, l2 = s2.Length;
        if (l1 != l2) return false;          // 如果长度都不相等,则必为 false

        int[] count = new int[26];           // 数组计数
        for (int i = 0; i < l1; i++) {
    
    
            count[s1[i] - 'a']++;            // s1 中出现的字符记录为 + 1 次
            count[s2[i] - 'a']--;            // s2 中出现的字符记录为 - 1 次
        }
        for (int i = 0; i < count.Length; i++) {
    
    
            if (count[i] != 0) return false; // 若最后记录结果不为 0,则返回 false
        }
        return true;                         // 否则返回 true
    }
}

Guess you like

Origin blog.csdn.net/zheliku/article/details/132352117