当前位置:网站首页>2021-06-25: a batch of strings consisting only of lowercase letters (a~z) are put

2021-06-25: a batch of strings consisting only of lowercase letters (a~z) are put

2022-06-24 08:27:00 Fuda scaffold constructor's daily question

2021-06-25: Only lowercase letters (a~z) A batch of strings , Are placed in an array of character types String[] arr in , If one of the two strings contains exactly the same type of characters , Just count the two strings as one class , such as :baacbba and bac Even if it is a kind of . return arr How many classes are there in ?

Fuda answer 2021-06-25:

Bit operation . Lowercase letters total 26 individual , integer 32 position , Enough .a To z Corresponding 0 To 26, Traversal string , If it is a, Integer second 0 Change into 1; If it is c, The whole type 2 A into 1. Then save to set in . Multiple strings , Repeat this operation . Finally get set Number of elements of , Is the required return value .

The code to use golang To write . The code is as follows :

package main

import "fmt"

func main() {
	arr := []string{"moonfdd", "fddmoon", "aabbcc", "abcde", "abecd"}
	ret := types2(arr)
	fmt.Println(ret)
}

func types2(arr []string) int {
	types := make(map[int]struct{})
	for _, str := range arr {
		key := 0
		for i := 0; i < len(str); i++ {
			key |= 1 << (str[i] - 'a')
		}
		types[key] = struct{}{}
	}
	return len(types)
}

The results are as follows :

picture

Zuo Shen java Code

原网站

版权声明
本文为[Fuda scaffold constructor's daily question]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210626141425315o.html