Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities
The picture is as follows
Make sense of
- The first thing we need to figure out is what is an anagram? Roughly speaking, if two words have exactly the same type and number of characters, even if they are in different positions, they can also be called anagram.
- According to the above concepts, judge whether two words belong to letter heterotopic word, judge whether the number of each letter in the string is exactly the same.
Thought analysis
There are basically three ways to do this: sort +hash + array.
- Convert the two strings into char Arrays and sort them, and then use the Arrays tool to compare the two Arrays for consistency.
- Create a Hash table, iterate over one of the characters and store the total number of characters in the Hash table, iterate over another string to retrieve the characters, find the number of characters in the Hash table, subtract one from the other string, and determine the number of data in the current Hash table
- Create an array of 26 characters and store them as the result of – ‘a’.
Code implementation
Violence sort + comparison
/** * Call API violence sort **@param s
* @param t
* @return boolean
*/
public boolean isAnagramMethod1(String s, String t) {
if(s.length() ! = t.length()) {return false;
}
char[] sChars = s.toCharArray();
Arrays.sort(sChars);
char[] tChars = t.toCharArray();
Arrays.sort(tChars);
return Arrays.equals(sChars, tChars);
}
Copy the code
It is an authentic Hash table
/** * Use hash tables to store valid location data **@param s
* @param t
* @return boolean
*/
public boolean isAnagramMethod2(String s, String t) {
if(s.length() ! = t.length()) {return false;
}
HashMap<Character, Integer> hashMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char charAt = s.charAt(i);
hashMap.put(charAt, hashMap.getOrDefault(charAt, 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
char charAt = t.charAt(i);
hashMap.put(charAt, hashMap.getOrDefault(charAt, 0) - 1);
if (hashMap.get(charAt) < 0) {
return false; }}return true;
}
Copy the code
Use arrays
/** * implement ** in array mode@param s
* @param t
* @return boolean
*/
public boolean isAnagramMethod3(String s, String t) {
if(s.length() ! = t.length()) {return false;
}
int[] ints = new int[26];
for (int i = 0; i < s.length(); i++) {
ints[s.charAt(i) - 'a'] + +; }for (int i = 0; i < t.length(); i++) {
char charAt = t.charAt(i);
ints[charAt - 'a']--;
if (ints[charAt - 'a'] < 0) {
return false; }}return true;
}
Copy the code