美文网首页
华为OD机试真题2023_Swift_100_猜字谜

华为OD机试真题2023_Swift_100_猜字谜

作者: 雾中探雪 | 来源:发表于2023-02-28 11:26 被阅读0次

    解题思路
    使用双层循环,外层谜面,内层谜底
    1、变序:判断交换顺序后是否相同
    2、去重:判断两个字符串去掉重复字符后是否一致
    3、如果上面两条都不符合,就添加字符串 "not found"

    Swift 解题过程
    // 猜字谜
        func HW2023001() {
            // 测试用例
    //        let line1 = "conection", line2 = "connection,today"
    //        let line1 = "bdni,wooood,bnid", line2 = "bind,wrong,wood"
    //        let line1 = "bdni,wooood", line2 = "bind,wrong,wood"
    //        let line1 = "like,wooooood", line2 = "bind,wrong,wood"
    //        let miMian = line1.components(separatedBy: ",")
    //        let miDi = line2.components(separatedBy: ",")
            // 正式代码
            let miMian = String(readLine()!).components(separatedBy: ",")
            let miDi = String(readLine()!).components(separatedBy: ",")
            var res: [String] = []
            for mian in miMian {
                var isFound = false
                for di in miDi {
                    // 判断两个字符串排序后是否一样
                    if mian.sorted() == di.sorted() {  // 变序
                        res.append(di)
                        isFound = true
                        break
                    }else if quchong(mian, di) {  // 去重
                        res.append(di)
                        isFound = true
                        break
                    }
                }
                if !isFound { res.append("not found") }
            }
            print(res.joined(separator: ","))
        }
        // 判断两个字符串去重后是否一样
        func quchong(_ mm: String, _ md: String) -> Bool {
            let mmlist = Set(Array(mm)).sorted()
            let mdlist = Set(Array(md)).sorted()
            return mmlist == mdlist ? true : false
        }
    

    相关文章

      网友评论

          本文标题:华为OD机试真题2023_Swift_100_猜字谜

          本文链接:https://www.haomeiwen.com/subject/elklldtx.html