Topic
Given, strings s and t, write a function to determine if it is a anagram of S.
Example 1:
Input:s = "Anagram", T = "Nagaram"
Output:true
Example 2:
Input:s = "Rat", t = "Car"
Output:false
Note:
Assume the string contains only lowercase alphabets.
Solution Ideas
The question means: whether the string s and T are composed of the same characters: for example, there are 2 a in S, 4 b,t if the same, it is called S and T is anagram.
If s and t have inconsistent lengths, the direct return is false.
Because the title assumes that all letters are lowercase, we use an int array of length 26, with each element to save the number of characters in S and T. If present in S, then--if present in ++;t, then--; In this case, if s and T are exactly the same, then each element in the array should be 0.
Code
class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; int[] count = new int[32]; for(int i = 0; i < s.length(); i++) { count[s.charAt(i) - ‘a‘]++; count[t.charAt(i) - ‘a‘]--; } for(int i:count) if(i != 0) return false; return true; }}
[Leetcode]242.valid Anagram