LeetCode242. 有效的字母异位词

242. 有效的字母异位词

给定两个字符串 *s* 和 *t* ,编写一个函数来判断 *t* 是否是 *s* 的字母异位词。

**注意:**若 *s* 和 *t* 中每个字符出现的次数都相同,则称 *s* 和 *t* 互为字母异位词。

示例 1:

复制代码
输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

复制代码
输入: s = "rat", t = "car"
输出: false

思路

  • 构建一个26大小的int数组nums,用来存放出现字母的个数
  • 先遍历s字符串,记录出现字母次数,若出现则numsi++
  • 后遍历t字符串,记录出现字母次数,若出现则numsi--
  • 最后再遍历一个,检验nums的各个元素是否都是0

代码

cpp 复制代码
class Solution {
public:
    bool isAnagram(string s, string t) {
        int nums[26] = {};
        int aAscii = int('a');
        if (s.size() == t.size()) {
            for (auto it = s.begin(); it != s.end(); it++) {
                nums[int(*it) - aAscii]++;
            }
            for (auto it = t.begin(); it != t.end(); it++) {
                nums[int(*it) - aAscii]--;
            }
            for (int i = 0; i < 26; i++) {
                if (nums[i] != 0) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }
};
相关推荐
Dream it possible!7 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊8 小时前
算法之双指针系列(一)
算法·leetcode
十二8 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
Pniubi10 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH10 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi10 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
careathers15 小时前
【数据结构】基于比较的排序算法 - 交换排序
数据结构·算法·排序算法
文丑颜不良啊15 小时前
LeetCode2081~2100题目解析
java·leetcode
H.莓飛16 小时前
【C++】【STL】vector_OJ题
linux·服务器·开发语言·数据结构·c++·visual studio
文丑颜不良啊17 小时前
LeetCode2061~2080题目解析
java·leetcode