Valid Anagram (E)

题目

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

Example 1:

  1. Input: s = "anagram", t = "nagaram"
  2. Output: true

Example 2:

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


题意

判断两个给定的单词(只包含小写字母)是否互为anagram,即字母组成相同但排列顺序不同的单词。

思路

如果只包含小写字母,只需要遍历每一个字符串,统计每个字符串中每个字母出现的次数即可。

也可以将字符串排序后逐个比较。

Follow up仍可以用Hash的思想进行处理,只不过不能只开一个简单的数组来当hash表。


代码实现

Java

Hash

  1. class Solution {
  2. public boolean isAnagram(String s, String t) {
  3. if (s.length() != t.length()) {
  4. return false;
  5. }
  6. int count[] = new int[26];
  7. for (int i = 0; i < s.length(); i++) {
  8. count[s.charAt(i) - 'a']++;
  9. count[t.charAt(i) - 'a']--;
  10. }
  11. for (int i = 0; i < 26; i++) {
  12. if (count[i] != 0) {
  13. return false;
  14. }
  15. }
  16. return true;
  17. }
  18. }

排序

  1. class Solution {
  2. public boolean isAnagram(String s, String t) {
  3. if (s.length() != t.length()) {
  4. return false;
  5. }
  6. char[] ss = s.toCharArray();
  7. char[] tt = t.toCharArray();
  8. Arrays.sort(ss);
  9. Arrays.sort(tt);
  10. for (int i = 0; i < ss.length; i++) {
  11. if (ss[i] != tt[i]) {
  12. return false;
  13. }
  14. }
  15. return true;
  16. }
  17. }

Follow up

  1. class Solution {
  2. public boolean isAnagram(String s, String t) {
  3. if (s.length() != t.length()) {
  4. return false;
  5. }
  6. Map<Character, Integer> map = new HashMap<>();
  7. for (int i = 0; i < s.length(); i++) {
  8. char c = s.charAt(i);
  9. if (!map.containsKey(c)) {
  10. map.put(c, 1);
  11. } else {
  12. map.put(c, map.get(c) + 1);
  13. }
  14. }
  15. for (int i = 0; i < t.length(); i++) {
  16. char c = t.charAt(i);
  17. if (!map.containsKey(c) || map.get(c) == 0) {
  18. return false;
  19. } else {
  20. map.put(c, map.get(c) - 1);
  21. }
  22. }
  23. return true;
  24. }
  25. }

JavaScript

  1. /**
  2. * @param {string} s
  3. * @param {string} t
  4. * @return {boolean}
  5. */
  6. var isAnagram = function (s, t) {
  7. if (s.length !== t.length) return false
  8. const cnt = new Map()
  9. for (const c of s) {
  10. if (!cnt.has(c)) cnt.set(c, 1)
  11. else cnt.set(c, cnt.get(c) + 1)
  12. }
  13. for (const c of t) {
  14. if (cnt.has(c) && cnt.get(c) > 0) cnt.set(c, cnt.get(c) - 1)
  15. else return false
  16. }
  17. return true
  18. }