[LeetCode]242. Valid Anagram(有效字谜)

242. 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.
(假定只有小写字母)

其实就是判断第一个字符串和第二个字符串是否包含同样的字母,顺序不一样而已

思路:

  • 第一反应用异或,用了好多例子回忆异或
  • 将字符串排序,比较各个位置上字母是否相同(排序导致效率低下)

代码如下:

#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size())//判断两个字符串长度是否相同
            return false;
        if(s.size() == 0)//判断两个字符串长度是否为空
            return true;
        sort(s.begin(), s.end());//将两个字符串排序
        sort(t.begin(), t.end());
        bool res;
        for(int i=0; i<s.size(); i++){
            res = s[i]^t[i];//相同为0 不同为1
            if(res == 1)
                return false;
        }
        return true;
    }
};
int main()
{
    //0 false; 1 true
    //异或 相同为0 不同为1
    /*
    char a0 = 'a';
    char a1 = 'b';
    char a2 = 'a';
    bool b = a0^a1;//1 bool类型
    int b1 = a0^a1;//3 int类型
    bool c = a0^a2;//0
    bool d = (a0^a1)^(a1^a0);//0
    b ^= (a1^a0);//1
    b1 ^= (a1^a0);//0
    cout << b << c << d << b1<< endl;//1 0 0 0
    */

    Solution a;
    string s = "aa";
    string t = "bb";
    string s1 = "ab";
    string t1 = "ba";
    cout << a.isAnagram(s, t) << endl;
    cout << a.isAnagram(s1, t1) << endl;
    return 0;
}
  • 写完之后才发现,根本不用比较一个个的字符,排序后两字符串应该完全相同,直接比较字符串就行。贴出代码:
class Solution {
public:
    bool isAnagram1(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return (s == t);
    }
};
  • 随后又想出来一个方法,定义一个数组counts来存储各个字母数量(默认值为0),字符串s增加各个字母数量,字符串t减少各个字母数量,最后判断数组counts是否每个元素都是0,只要有一个元素不为0,返回false,否则返回true,贴出代码:
bool isAnagram2(string s, string t) {
        if(s.size() != t.size())//判断两个字符串长度是否相同
            return false;
        int counts[26] = {0};
        for(int i=0; i<s.size(); i++){
            counts[s[i]-'a']++;
            counts[t[i]-'a']--;
        }
        for(int m=0; m<26; m++){
            if(counts[m])//counts[m]!=0
                return false;
        }
        return true;
    }
  • 在网上看到了一个利用Hash Table的方法,思路大致相同
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        int n = s.length();
        unordered_map<char, int> counts;
        for (int i = 0; i < n; i++) {
            counts[s[i]]++;
            counts[t[i]]--;
        }
        for (auto count : counts)
            if (count.second) return false;
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值