LeetCode#242 Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
分析
既然只有小写字母,那就可以通过一个长度为26的数组记录第一个字符串中的字符出现的次数,再通过遍历第二个字符串并做减法,如果某个字符对应的次数小于0,则说明两个字符串不是变位词。1
2
3
4
5
6
7
8
9
10
11
12boolean isAnagram(s1, s2)
count = new int[26]
chars1 = s1.toCharArray()
for (c in chars1)
count[c - 'a']++
chars2 = s2.toCharArray()
for (c in chars2)
if (count[c - 'a']-- == 0)
return false
return true