题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
package main //建立一个map叫做command依次存放所有存在的命令组合, //如果这个key存在 则重置为unknow 例"b a"第一次存放时command["b a"]="where to add" //第二次在“backplane abort”也会存在"b a"命令,此时将command["b a"]="unknown command" //读取屏幕输入以回车结束 import ( "bufio" "fmt" "os" ) func main() { command := make(map[string]string) un := "unknown command" initMap("reset", "", "reset what", un, command) initMap("reset", "board", "board fault", un, command) initMap("board", "add", "where to add", un, command) initMap("board", "delete", "no board at all", un, command) initMap("reboot", "backplane", "impossible", un, command) initMap("backplane", "abort", "install first", un, command) sc := bufio.NewScanner(os.Stdin) for sc.Scan() { cmd := sc.Text() //判断cmd命令是否存在于map todo, ok := command[cmd] if ok { fmt.Println(todo) } else { fmt.Println(un) } } } func initMap(first string, second string, todo string, unknow string, comd map[string]string) { if len(second) == 0 { for i := 0; i < len(first); i++ { comd[first[:i+1]] = todo } } else { for i := 0; i < len(first); i++ { for j := 0; j < len(second); j++ { if _, ok := comd[first[:i+1]+" "+second[:j+1]]; !ok { comd[first[:i+1]+" "+second[:j+1]] = todo } else { comd[first[:i+1]+" "+second[:j+1]] = unknow } } } } }