Example of Golang string anagram in detail
- 2020-06-07 04:39:07
- OfStack
Achieve the goal
The goal of this article is to write a function anagram(s, t) to determine if two strings are formed alphabetically. Without further ado, let's take a look at the details.
GoLang implementation
func solution(s , t string)bool{
if s == t {
return true
}
length := len(s)
if length != len(t) {
return false
}
//' ' 32 --> ~ 126
const MAX_ASCII int= 94
const SPACE_INDEX rune = 32
numbers := [MAX_ASCII]int{}
sRune := []rune(s)
tRune :=[]rune(t)
for i := 0 ; i < length ; i++ {
index := tRune[i] - SPACE_INDEX
numbers[index]++
index = sRune[i] - SPACE_INDEX
numbers[index]--
}
for i := 0 ; i < MAX_ASCII / 2 ; i++{
mergeSize := numbers[i]
if mergeSize != 0 || mergeSize != numbers[MAX_ASCII - 1 - i]{
return false
}
}
return true
}
Key point 1:
Defines the value that holds the last value to determine whether two strings are the same length:
According to the ASCII table:
The difference between the first single character "" in decimal 32 and the last single character" ~ "in decimal 126 is 94.
The prediction here is that each character has been used, so the length is simply defined as 94.
The Java implementation is similar to the above:
public boolean anagram(String s, String t) {
if (s == null || t == null || s.length() ==0 || s.length() != t.length()){
return false;
}
if (s.equals(t))return true;
final int MAX_ASCII = 94;
final char SPACE_INDEX = ' ';
int[] numbers = new int[MAX_ASCII];
int length = s.length();
char[] sCharArray = s.toCharArray();
char[] tCharArray = t.toCharArray();
for(int i = 0 ; i< length ; i++){
int index = sCharArray[i] - SPACE_INDEX;
numbers[index]++;
index = tCharArray[i] - SPACE_INDEX;
numbers[index]--;
}
for (int i =0 ; i < MAX_ASCII / 2 ; i++ ) {
int mergeSize = numbers[i];
if ( mergeSize != 0 || mergeSize != numbers[MAX_ASCII - 1 - i]){
return false;
}
}
return true;
}
conclusion