leetcode 242. 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.

最简单直接的方法就是直接HashMap统计即可。

代码如下:

import java.util.HashMap;

/*
 * 注意使用Map数据结构
 * */
public class Solution 
{
    public boolean isAnagram(String s, String t) 
    {
        if(s==null && t==null)
            return true;
        else if(s==null && t!=null || s!=null && t==null || s.length()!=t.length())
            return false;

        HashMap<Character, Integer> map1=new HashMap<>();
        HashMap<Character, Integer> map2=new HashMap<>();
        for(int i=0;i<s.length();i++)
        {
            if(map1.containsKey(s.charAt(i)))
                map1.put(s.charAt(i), map1.get(s.charAt(i))+1);
            else
                map1.put(s.charAt(i), 0);

            if(map2.containsKey(t.charAt(i)))
                map2.put(t.charAt(i), map2.get(t.charAt(i))+1);
            else
                map2.put(t.charAt(i), 0);
        }
        return map1.equals(map2);
    }
}

下面是C++的做法,就是使用一个26大小的数组纪录每一个字母出现的频率,也可以直接使用map做记录然后比较

代码如下:

#include <iostream>
#include <alogrithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>

using namespace std;

class Solution 
{
public:
    bool isAnagram(string s, string t) 
    {
        vector<int> a(26,0);
        for (char i : s)
            a[i - 'a']++;
        for (char i : t)
        {
            a[i - 'a']--;
            if (a[i - 'a'] < 0)
                return false;
        }
        for (int i : a)
        {
            if (i > 0)
                return false;
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值