算法 Java Leetcode Golang

Determine if t is an anagram of s.

Question

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

1
2
3
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Hint

  1. You may assume the string contains only lowercase alphabets.
  2. What if the inputs contain unicode characters?

Solution in Java, C++ and Golang

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