题解 | 查找兄弟单词

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

// 获取输入内容
func getInputText() (count int, brother []string, words string, index int) {
    reader := bufio.NewReader(os.Stdin)
    inputText, _ := reader.ReadString('\n')
    inputText = strings.TrimSuffix(inputText, "\n")
    inputSlice := strings.Split(inputText, " ")

    // 字符串个数
    count, _ = strconv.Atoi(inputSlice[0])
    // 兄弟字符串
    brother = inputSlice[1:len(inputSlice) - 2]
    // 指定字符串
    words = inputSlice[len(inputSlice) - 2]
    // 指定兄弟单词的序号
    index, _ = strconv.Atoi(inputSlice[len(inputSlice) - 1])
    return
}

func main() {
    _, brother, words, index := getInputText()
    // fmt.Println(brother, words, index)
    res := make([]string, 0) // 符合条件字符串
    // 记录指定字符串每个字母出现的次数
    tagMap := make(map[string]int)
    for _, v := range words {
        tagMap[string(v)]++
    }

    for _, wordsItem := range brother {
        if len(string(wordsItem)) < 2 || len(string(wordsItem)) != len(words) || string(wordsItem) == words {
            continue
        }
        itemMap := make(map[string]int)
        for _, v := range string(wordsItem) {
            itemMap[string(v)]++
        }
        flag := 0
        for k, _ := range tagMap {// 两个map作比较
            if itemMap[string(k)] != tagMap[string(k)] {
                flag = 1
            }
        }
        if flag == 0 {
            res = append(res, string(wordsItem))
        }
    }

    sort.Strings(res)

    fmt.Println(len(res))
    if len(res) < index{
        return
    }
    fmt.Print(res[index-1])
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务