Easy
814116FavoriteShare
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?
排序法:
Java:
/*
* @Author: SourDumplings
* @Date: 2019-08-29 13:02:49
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/valid-anagram/
*/
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
/*
* @Author: SourDumplings
* @Date: 2019-08-29 12:56:03
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/valid-anagram/
*/
class Solution
{
public boolean isAnagram(String s, String t)
{
if (s.length() != t.length())
{
return false;
}
char[] c1 = s.toCharArray();
char[] c2 = t.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
int l = c1.length;
for (int i = 0; i < l; i++)
{
if (c1[i] != c2[i])
{
return false;
}
}
return true;
}
}
散列表(Hashtable):
Java:
import java.util.Hashtable;
import java.util.Map;
/*
* @Author: SourDumplings
* @Date: 2019-08-29 12:56:03
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/valid-anagram/
*/
class Solution
{
public boolean isAnagram(String s, String t)
{
Map<Character, Integer> m1 = new Hashtable<>();
Map<Character, Integer> m2 = new Hashtable<>();
int l1 = s.length();
int l2 = t.length();
for (int i = 0; i < l1; i++)
{
Character c = s.charAt(i);
if (!m1.containsKey(c))
{
m1.put(c, 1);
}
else
{
m1.put(c, 1 + m1.get(c));
}
}
for (int i = 0; i < l2; i++)
{
Character c = t.charAt(i);
if (!m2.containsKey(c))
{
m2.put(c, 1);
}
else
{
m2.put(c, 1 + m2.get(c));
}
}
return m1.equals(m2);
}
}
红黑树(map):
C++:
/*
* @Author: SourDumplings
* @Date: 2019-08-29 12:51:45
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/valid-anagram/
*/
class Solution
{
public:
bool isAnagram(string s, string t)
{
map<char, int> m1, m2;
for (auto &&c : s)
{
++m1[c];
}
for (auto &&c : t)
{
++m2[c];
}
return m1 == m2;
}
};