Valid Anagram(有效变位词)

Given two strings s and t, write a function to determine if t is an anagram of s.(给定两个字符串s和t,判断字符串t是否是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.(可假设字符串只包含小写字母)

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?(如果输入包含unicode字符又如何处理?)

1.个人分析
所谓的变位词就是两个字符串的元素集合是相同的,只不过两者的排序不同。
思路:
(1)如果字符串中只包含字母,那么就可以统计每个字母的个数,然后对两个统计结果进行比较,若两字符串所包含的字母类型和个数都相同则返回true,否则返回false。
(2)将两字符串进行排序,然后从头到尾遍历比较,遇到不同字符就返回false,否则返回true。

2.个人解法
思路(1)对应的代码实现:

bool isAnagram(string s, string t)
{
    int sLetterCount[26] = {0};
    int tLetterCount[26] = {0};

    for (int i=0; i<s.length(); ++i)
        ++sLetterCount[s[i] - 'a'];

    for(int i=0; i<t.length(); ++i)
        ++tLetterCount[t[i] - 'a'];

    for (int i=0; i<26; ++i)
    {
        if(sLetterCount[i] != tLetterCount[i])
            return false;
    }

    return true;
}

思路(2)对应的代码实现:

bool isAnagram2(string s, string t)
{
    if(s.length() != t.length())
        return false;

    sort(s.begin(), s.end());
    sort(t.begin(), t.end());

    for (int i=0; i<s.length(); ++i)
    {
        if(s[i] != t[i])
            return false;
    }

    return true;
}

结果显示思路(1)解法的运行时间是思路(2)的八分之一,但解法二适合任意字符的情况。解法一本质上是利用了哈希表的高效查找。

3.参考解决方法

bool isAnagram3(string s, string t)
{
    if(s.length() != t.length())
        return false;

    int counter[26] = {0};

    for (int i=0; i<s.length(); ++i)
    {
        ++counter[s[i] - 'a'];
        --counter[t[i] - 'a'];
    }

    for(int i=0; i<26; ++i)
    {
        if(counter[i] != 0)
            return false;
    }

    return true;
}

这种解法本质与自己的第一方法是一样的,但这里只定义了一个计数数组,通过在该数组上同时进行加减操作,如果两字符串包含的内同相同的话,数组的所有元素值应该为0返回true,否则返回false。

对于任意字符的情况:
Use a hash table instead of a fixed size counter. Imagine allocating a large size array to fit the entire range of unicode characters, which could go up to more than 1 million. A hash table is a more generic solution and could adapt to any range of characters.(使用哈希表而不是用一个固定大小的计数器;如果创建一个要涵盖所有unicode 字符的数组,这个规模将会超过一百万;相对来说使用哈希表是更加可行的解决方法,因为它能够适用任意范围的字符)

4.总结
目前来看,所遇到关于字符串和数组的题目,最优解法似乎都会借助哈希表实现,也正是哈希表在查找方面的高效才为实现最优解法提供了有利工具。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值