考察的知识点:字符串;

解答方法分析:

  1. 函数会比较两个字符串的长度,如果它们的长度不相等,直接返回false。
  2. 创建两个unordered_map<char, int>类型的变量countS和countT,用于记录字符串中每个字符出现的次数。
  3. 使用一个循环遍历字符串s,将每个字符添加到countS中,并对应地增加该字符的计数。
  4. 使用另一个循环遍历字符串t,将每个字符添加到countT中,并对应地增加该字符的计数。
  5. 使用一个循环遍历字符串s的每个字符,检查在countS和countT中该字符的计数是否相等,如果有任何一个字符的计数不相等,就返回false。
  6. 如果以上循环结束后都没有返回false,则说明两个字符串的字符组成完全相同,函数返回true。

所用编程语言:C++;

完整编程代码:↓

class Solution {
  public:
    bool areHerdCompositionsEqual(string s, string t) {
        if (s.length() != t.length()) {
            return false;
        }
        unordered_map<char, int>
        countS;
        unordered_map<char, int>
        countT;
        for (char ch : s) {
            countS[ch]++;
        }
        for (char ch : t) {
            countT[ch]++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (countS[s[i]] != countT[t[i]]) {
                return false;
            }
        }
        return true;
    }
};