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.

分析

首先能够想到的是,为st分别建立一个HashMap,统计每个字母出现的次数,比较两个HashMap是否相等。时间复杂度O(n),空间复杂度O(n)n为字符串长度。

如果面试官要求空间复杂度均为O(1),怎么办?

注意这题的字符串只包含小写的字母,意味着只有从a-z的26个字母,于是我们可以为st开一个长度为26的整数数组来代替哈希表,此时额外空间为固定长度的两个数组,因此为O(1)。这是这题比较狡诈的地方。

代码

  1. // Valid Anagram
  2. // Time Complexity: O(n), Space Complexity: O(1)
  3. public class Solution {
  4. public boolean isAnagram(String s, String t) {
  5. if (s.length() != t.length()) return false;
  6. final int[] map = new int[ALPHABET_SIZE];
  7. for (int i = 0; i < s.length(); ++i) {
  8. ++map[s.charAt(i) - 'a'];
  9. --map[t.charAt(i) - 'a'];
  10. }
  11. for (int x : map) {
  12. if (x != 0) return false;
  13. }
  14. return true;
  15. }
  16. private static final int ALPHABET_SIZE = 26;
  17. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/valid-anagram.html