The function of the function is to remove duplicate elements from the input string slice and return the deduplicated result. The specific implementation logic is as follows:
- Create an empty result slice
result
for storing deduplicated strings. - Create a temporary map
tempMap
for storing unique strings. The keys of the map are strings and the values are bytes. slc
Iterate over each element in the input string slicee
:- First, get
tempMap
the length and assign it to a variablel
. - Then, use the string
e
as the key, set the value to 0, and store ittempMap
in. - If the length of is changed
tempMap
after the addition (that is, an element that does not exist is successfully added), it means that the element appears for the first time and is not repeated.tempMap
- Append this element
e
to the result sliceresult
.
- Append this element
- First, get
- After traversing all elements, return the result slice
result
, which is the result after deduplication.
// 通过map主键唯一的特性过滤重复元素
func RemoveDuplicateStrings(strs []string) []string {
result := []string{}
tempMap := map[string]byte{} // 存放不重复字符串
for _, e := range strs {
l := len(tempMap)
tempMap[e] = 0
if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复
result = append(result, e)
}
}
return result
}