MENU

LeetCode242. Valid Anagram(模拟)

2019 年 02 月 14 日 • 阅读: 880 • LeetCode阅读设置

LeetCode242. Valid Anagram(模拟)

  • Easy
  • Accepted:295,264
  • Submissions:582,802

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?


链接

https://leetcode.com/problems/valid-anagram/

题意

给定两个字符串s和t,判断t是否是s的anagramanagram 的意思是由颠倒字母顺序而构成的字。之前我们在LeetCode438. Find All Anagrams in a String(滑动窗口)提到过。

题解

  • 排序后判断是否相同,时间复杂度$O(nlogn + mlogm)$
  • 用个cnt计数数组记录一遍然后开始匹配,具体看代码,时间复杂度$O(n + m)$

代码

  • Runtime: 12 ms, faster than 96.12% of C++ online submissions for Valid Anagram.
  • Memory Usage: 9 MB, less than 100.00% of C++ online submissions for Valid Anagram.
class Solution {
public:
    bool isAnagram(string s, string t) {
        int n = s.length(), m = t.length();
        int tot = n;
        int cnt[256] = {0};
        for (int i = 0; i < n; ++i)
            cnt[s[i]]++;
        for (int i = 0; i < m; ++i)
        {
            if (cnt[t[i]]-- > 0)
                --tot;
            // else return 0;
        }
        return tot == 0 && n == m; // 需要判断是否相等,"a" / "ab"
    }
};

注意需要判断s和t的长度是否相同。


The end.
2019年2月14日 星期四