首页 > 其他 > 详细

242.Valid Anagram

时间:2020-04-21 00:31:49      阅读:89      评论:0      收藏:0      [点我收藏+]

题目描述

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

难度系数

Medium

解法一:排序后比较

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        return s==t;
    }
};

 

解法二:记录每个字符串中字母出现的次数

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

 

 

242.Valid Anagram

原文:https://www.cnblogs.com/AntonioSu/p/12741562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!