算法
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
- You may assume the string contains only lowercase alphabets.
- What if the inputs contain unicode characters?
Solution in Java, C++ and Golang
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; } }
|
1 2 3 4 5 6 7 8
| class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(),s.end()); sort(t.begin(),t.end()); return s==t; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| func isAnagram(s string, t string) bool { if len(s) != len(t) { return false } var counter [26]int for i := 0; i < len(s); i++ { counter[s[i] - 'a']++ counter[t[i] - 'a']-- } for _, count := range counter { if count != 0 { return false } } return true }
|