友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

242. Valid Anagram

两种解法都可以,还是要多做题啊!

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?

思路分析

  • 一刷

  • 二刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * Runtime: 3 ms, faster than 93.97% of Java online submissions for Valid Anagram.
 *
 * Memory Usage: 36.2 MB, less than 98.06% of Java online submissions for Valid Anagram.
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-01-10 23:48
 */
public boolean isAnagram(String s, String t) {
    if (Objects.isNull(s) && Objects.isNull(t)) {
        return true;
    }
    if (Objects.isNull(s) || Objects.isNull(t)) {
        return false;
    }
    int[] sChartCount = new int[26];
    for (char c : s.toCharArray()) {
        sChartCount[c - 'a']++;
    }
    int[] tChartCount = new int[26];
    for (char c : t.toCharArray()) {
        tChartCount[c - 'a']++;
    }
    return Arrays.equals(sChartCount, tChartCount);
}

/**
 * Runtime: 3 ms, faster than 93.97% of Java online submissions for Valid Anagram.
 *
 * Memory Usage: 37.9 MB, less than 64.51% of Java online submissions for Valid Anagram.
 */
public boolean isAnagramSort(String s, String t) {
    char[] sChars = s.toCharArray();
    Arrays.sort(sChars);
    char[] tChars = t.toCharArray();
    Arrays.sort(tChars);
    return Arrays.equals(sChars, tChars);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-01-10 23:48
 */
public boolean isAnagram(String s, String t) {
  if (s.length() != t.length()) {
    return false;
  }
  int[] chars = new int[26];
  for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    chars[c - 'a']++;
  }
  for (int i = 0; i < t.length(); i++) {
    char c = t.charAt(i);
    chars[c - 'a']--;
    if (chars[c - 'a'] < 0) {
      return false;
    }
  }
  for (int cnt : chars) {
    if (cnt != 0) {
      return false;
    }
  }
  return true;
}