[242] Valid Anagram

来源:互联网 发布:因特网属于什么网络 编辑:程序博客网 时间:2024/05/17 03:14

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;        }    }};
0 0
原创粉丝点击