Leetcode刷题Day10|有效的字母异位词

Leetcode刷题Day10|有效的字母异位词

1.题目描述

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

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

提示:

  • 1 <= s.length, t.length <= 5 * 104
  • st 仅包含小写字母

2.题解

哈希表

class Solution {
public:
    bool isAnagram(string s, string t) {
        std::unordered_map<char,int> count;
        for(char c:s){
            count[c]++;
        }

        for(char c:t){
            if(count[c]==0)return false;
            count[c]--;
        }
        for(char c:s){
            if(count[c]!=0)return false;
        }
        return true;
    }
};

思路

使用哈希表先统计s中字母频率,存入count,再遍历t,如果t中有s中没有的字母,返回false,如果存在相同字母,count中减1,最后遍历s,如果不全为0,就返回false,全为0就返回true。

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值