Given, Strings s and T, write a function to determine if it is a anagram of s. /c1>
For example,
S = "Anagram", t = "Nagaram", return true.
s = "Rat", t = "Car", return false.
Note:
assume the string contains only lowercase alphabets.
Problem Solving Ideas:
Returns true as long as the characters of S and T and the same number of characters are used. The characters used in this question are lowercase, so you can use a fixed-size array as a hash array, recording the number of occurrences of a character in a string ....
class Solution { Public : //12ms bool Isanagram (string s, String t) { int n=s.length (); if(N!=t.length ())return false; if(n==0)return true; int a[26]={0}; For (int i=0;i<n;i++) { a[s[i]-' a ']++; a[t[i]-' a ']--; } For (int i=0;i<26;i++) if(a[i]!=0)return false; return true; } }; Or class Solution { Public : //12ms bool Isanagram (string s, String t) { int n=s.length (); if(N!=t.length ())return false; if(n==0)return true; int a[26]={0}; For (int i=0;i<n;i++) { a[s[i]-' a ']++; } For (int i=0;i<n;i++) if(a[t[i]-' a ']==0)return false; Else a[t[i]-' a ']--; return true; } }; |
Another way is to use map to record the number of occurrences of each character, the process is similar to ...
242. Valid Anagram