leetcode-242-Valid Anagram

题目描述:

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

 

要完成的函数:

bool isAnagram(string s, string t) 

 

说明:

1、给定两个字符串 s 和 t ,要求判断 s 能不能通过交换位置变成 t ,返回true或者false。

2、其实就是要我们判断 s 和 t 中的字符出现次数是不是相等,而且两个字符串中只包含小写字母,所以我们定义一个长度为26的vector就可以了。

代码如下:(附详解)

    bool isAnagram(string s, string t) 
    {
        int s1=s.size(),s2=t.size(),res=0;
        if(s1!=s2)//边界条件
            return false;
        vector<int>count(26,0);//定义一个长度26的vector
        for(int i=0;i<s1;i++)
        {
            count[s[i]-'a']++;//s中的字母要加1
            count[t[i]-'a']--;//t中的字母要减1
        }
        for(int i=0;i<26;i++)
        {
            if(count[i]!=0)//判断最终的26个数值是不是都为0
                return false;
        }
        return true;
    }

上述代码实测10ms,beats 99.39% of cpp submissions。

 

3、其他想法(不是那么重要)

笔者曾经产生过一个想法,用异或来做这道题,如果两个字符串的所有字母都一样,那么必然所有字母的异或结果为0,如果不一样,比如“ab”和“ac”,那么异或结果必然不为0。

这样子判断起来会快很多。

但是存在一个问题,如果两个字符串是“aa”和“bb”,异或结果仍然是0,这就很尴尬了。

所以其实异或结果是0,是两个字符串中的所有字母都一样的,必然条件,而不是充分条件。

最终还是用统计的方法完成了。

猜你喜欢

转载自www.cnblogs.com/king-3/p/9117422.html