Topic:
Given, Strings s and T, write a function to determine if it is a anagram of s.
For example,
s = "Anagram", t = "Nagaram", return true.
s = "Rat", t = "Car", return false.
Analysis:
Criteria for distinguishing "anagram":
1. Two characters are exactly equal and two numbers are completely empty: true
2. Two characters unequal length: false
3. The number of occurrences of the same character is not equal: false
The code is as follows:
Public classSolution { Public Static inthascharacter (String Basic, String Target) { for(inti = 0;i<basic.length (); i++){ if(Basic.substring (i, i+1) = =Target) { returni; } } return-1; } Public Static BooleanIsanagram (string s, String t) {if(S.length ()! =t.length ()) { return false; } if(s = =t) { return true; } for(intI=0;i<t.length (); i++){ intIflag = Hascharacter (s,t.substring (i, i+1)); if(Iflag = =-1){ return false; } Else{s= S.substring (iflag,iflag+1); } } return true; }}
Master's idea: convert two characters to a string and then compare them after sorting
Public Static BooleanIsanagram (string s, String t) {if(s = = T | | (S.equals ("") && t.equals (""))){ return true; } if(S.length ()! =t.length ()) { return false; } Char[] CharS =S.tochararray (); Char[] CharT =T.tochararray (); Arrays.sort (CharS); Arrays.sort (CharT); returnchars.equals (CharT); }
[Leetcode]: 242:valid anagram