【LeetCode】马三来刷题之Valid Anagram

刷题第3天,题目链接:https://leetcode.com/problems/valid-anagram/

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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

两种思路,第一种方法将数组排序以后,再比较,如果相同就返回true,否则返回false。第二种方法,建立一个map统计两个字符串中每个字母出现的次数,s中每出现一个字母就将对应键的值++,t中每出现一个字母就将对应键的值--。最后统计map中所有元素的键值,一旦发现有值不为0的就返回false,否则返回true。

方法一:

bool isAnagram(string s, string t) {
    sort(s.begin(),s.end());
    sort(t.begin(),t.end());
    if(s.compare(t)==0)return true;
    else return false;
}
方法二:

bool isAnagram(string s, string t) {
    map<char,int> m;
    if(s.length()!=t.length())return false;
    for(int i=0;i<s.length();i++){
        m[s[i]]++;
        m[t[i]]--;
    }
    for(map<char,int>::iterator it=m.begin();it!=m.end();it++){
        if((*it).second!=0)return false;
    }
    return true;
}

在网上看到了一种与方法二类似的解法,只不过使用数组模拟的,更加巧妙,比map更节省空间,所以也把解法搬运了过来:

方法三:

        vector<int> count(26, 0);
        for(int i = 0; i < s.size(); i ++)
            count[s[i]-'a'] ++;
        for(int i = 0; i < t.size(); i ++)
            count[t[i]-'a'] --;
        for(int i = 0; i < 26; i ++)
            if(count[i] != 0)
                return false;
        return true;
    }


每天一道题,保持新鲜感,就这样~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值