242. Valid Anagram

来源:互联网 发布:网络摄像头搜不到ip 编辑:程序博客网 时间:2024/06/08 10:21

1.Question

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.

2.Code
class Solution {public:    bool isAnagram(string s, string t) {        if (s.size() != t.size()) return false;        int m[26] = {0};        for (int i = 0; i < s.size(); i++)            m[s[i] - 'a']++;        for (int i = 0; i < t.size(); i++)            if (--m[t[i] - 'a'] < 0)                return false;        return true;    }};
3.Note

a.要使用string类,就需要加入头文件#include<string>,其中 .size()和 .length()的效果是一样的,.length()是延承了C语言的习惯。

b.本题的思想就是哈希表,这是一种简单的哈希表。

c.以下是写的第一版答案,在leetcode跑完是16ms,上面的代码是12ms。差距在于,某些情况并不需要遍历t 则可以return false,而下面的代码是先遍历了s和t 再进行判断的。

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



1 0
原创粉丝点击