leetCode---Valid Anagram

一. 题目: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?
Subscribe to see which companies asked this question.

二. 思路分析

        首先先判断两个字符串的长度是否一样,若不一样则返回false;定义一个包含26个整数的数组Num,用于保存每个字母出现的次数,遍历字符串s,将每个字母出现的次数记录在数组Num里;再次遍历字符串t,若该字母对应的位置存储的值为0,则代表该字母为s没出现过或s出现过,但是已经被t之前的字母抵消,即该字母在s中无法找到想匹配的字母,返回false;若对应位置存储的值不为0,则值自减1,表示s中的该字母被抵消了一个。代码如下:
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()){
            return false;
        } 
        int nums[26]={0};
        for(int i = 0; i < s.size(); i++){
            nums[s[i] - 'a']++;
        }
        for(int i = 0; i < t.size(); i++){
            if(nums[t[i] - 'a'] == 0){
                return false;
            } else{
                nums[t[i] - 'a']--;
            }
        }
        return true;
    }
};
Follow out
What if the inputs contain unicode characters? How would you adapt your solution to such case?
使用哈希表实现,在c++中可以用stl中的map实现。若按照上面的方法为unicode的每个字符都开辟一个数组元素,则该数组将会非常之大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值