[242] Valid Anagram

1. 题目描述

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
题目意思为判定两个字符串是否为同字母异序词,根据例子来看,同字母异序词表示所包含字母相同但排列次序不同的两个单词,另外题目假定两个单词都只使用小写字母。

2. 解题思路

题目的关键在于两个点,①同字母②异序
包含字母是否相同我想到的是统计词频,若每个字母出现的频率相同而两个单词又不相同则两个单词为同字母异序词,在这里我使用的判断词频是否相等的方法是创建一个一维数组包含26个位置,对s和t进行一次遍历,过程如下图,当遍历完成后数组所有元素为0,即为词频相同。
这里写图片描述

边界条件

这里有一些边界是我一开始没有想到的,包括①两个字符串为空时②两个字符串都是只有一个字母并且相同时,都满足同字母异序

3. Code

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s == "" && t == "")  // s=t=空
            return true;
        // s=t='a'
        if(s == t && s.length() == 1 && t.length() == 1)
            return true;
        else if(s == t)  // s与t完全相等
            return false;
        else if(s.length() != t.length())  // s与t长度不同
            return false;
        else
        {
            int* statistic = new int[26];  // 保存词频
            // 初始化statistic全为0
            for(int init(0); init < 26 ; ++init)
            {
                statistic[init] = 0;
            }
            for(int i(0); i<s.length(); ++i)
            {
                statistic[s[i]-'a']++;  // 对应位置+1
                statistic[t[i]-'a']--;  // 对应位置-1
            }
            // 若s,t词频相等则statistic全为0
            for(int j(0); j < 26; ++j)
            {
                if(statistic[j] != 0){
                    delete[] statistic;
                    return false;
                }
            }
            delete[] statistic;
            return true;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值