leetcode242

1、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.
对于无序的数字呀或者字母呀,要统计每个类型的出现次数,无序容器比较好用~~

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) return false;
        int n = s.size();
        unordered_map<char,int> result;
        for(int i = 0; i < n; i++){
            result[s[i]] ++;
            result[t[i]] --;
        }
        for(auto i : result)               //容器遍历
            if(i.second) return false;
        return true;
    }
};

1、容器遍历有以下几种方式:

  • 采用迭代器,并采用C++11新标准中的auto关键字,
for(auto i = result.begin(); i != result.end(); i++)
    if((*i).second) return false;
    //auto=unordered_map<char,int>::iterator
  • 采用下角标进行数据元素访问
    对一个map进行下标操作时,会获得一个mapped_type对象(map类的值);但当解引用一个map迭代器时,得到一个value_type对象(pair),只有得到一个pair对象,才可以a.second….这样用~
vector<int> aaa;
for(int i = 0; i < aaa.size(); i++)
    if(aaa[i]) return false;

不过之前我们也总结过,遇到字母可以将其转换为ASCII码处理起来比较快,同时也可以将字母直接的关系转换成数字直接的运算。
题中说都是小写字母,s[i] - ‘a’这样的转换就可以将每个字母转换为数字。。。

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        int n = s.length();
        int counts[26] = {0};
        for (int i = 0; i < n; i++) { 
            counts[s[i] - 'a']++;
            counts[t[i] - 'a']--;
        }
        for (int i = 0; i < 26; i++)
            if (counts[i]) return false;
        return true;
    }
};

还有一种简单粗暴的方式就是,既然是回文字,排序后就会是一模一样的啦

class Solution {
public:
    bool isAnagram(string s, string t) { 
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t; 
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值