题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
package main import ( "fmt" "sort" ) func isBrotherWord(word1, word2 string) bool { if len(word1) != len(word2) { return false } if word1 == word2 { return false } count1 := make([]int, 26) count2 := make([]int, 26) for i := 0; i < len(word1); i++ { count1[word1[i]-'a']++ count2[word2[i]-'a']++ } for i := 0; i < 26; i++ { if count1[i] != count2[i] { return false } } return true } func main() { var n int fmt.Scan(&n) words := make([]string, n) for i := 0; i < n; i++ { fmt.Scan(&words[i]) } var x string fmt.Scan(&x) var k int fmt.Scan(&k) brotherWords := make([]string, 0) for _, word := range words { if isBrotherWord(word, x) { brotherWords = append(brotherWords, word) } } sort.Strings(brotherWords) m := len(brotherWords) fmt.Println(m) if k < m { fmt.Println(brotherWords[k-1]) } }
思路: 首先将输入的n个单词存储到一个列表中。
题目要求我们找到给定单词 x 的兄弟单词中按字典序排列的第 k 个单词。
首先,我们需要定义一个函数来判断两个单词是否是兄弟单词。可以通过比较两单词的字符排序后是否相等来实现。
接下来,我们可以使用一个数组或者集合来存所有满足条件的兄弟单词遍历给定的词列表,对于每个单词,如果它不等于 x 并且与 x 是兄弟单词,则将其添加数组或集合中。
最后,对存储兄弟单词的数组或集合进行排序,并输出第 k 单词。
以下是一个可能的 Go 语言实现:
package main import ( "fmt" "sort" ) // 判断两个词是否是兄弟单词 func isBrotherWord(word1, word2 string) bool { if word1 == word2 { return false } sorted1 := sortString(word1) sorted2 := sortString(word2) return sorted1 == sorted2 } // 对字符串进行排序 func sortString(s string) string { runes := []rune(s) sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] }) return string(runes) } func main() { var n int fmt.Scan(&n) words := make([]string, n) for i := 0; i < n; i++ { fmt.Scan(&words[i]) } var x string fmt.Scan(&x) var k int fmt.Scan(&k) brotherWords := make([]string, 0) for _, word := range words { if isBrotherWord(word, x) { brotherWords = append(brotherWords, word) } } sort.Strings(brotherWords) m := len(brotherWords) fmt.Println(m) if k <= m { fmt.Println(brotherWords[k-1]) } }
这个实现中我们首先定义了 isBrotherWord
函数来判断两个单词是否是兄弟单词。然后,我们使用 sortString
函数对字符串进行排序。
在 main
函数中,我们首先读取输入的 n、单词列表和 x。然后,我们遍历单词列表,找到所有满足条件的兄弟单词,并它们存储在 brotherWords
数组中。接下来,我们对 brotherWords
进行排序,并输出兄单词的个数 m。最后,如果 k 小于等于 m,则输出按字典序排列后的第 k 个兄弟单词。
注意:以上代码仅为示,可能需要根据具的输入输出格式进行调整。