华为OD机试真题2023_Swift_100_箱子之形摆放

// 箱子之形摆放
    func HW2023026() {
//        let inputStr = "ABCDEFG 3"
        let inputStr = String(readLine()!)
        let inputArr = inputStr.components(separatedBy: " ")
        let input = inputArr[0]
        let n = Int(inputArr[1])!
        var mapDic: [Int: String] = [:] // 将箱子的行数及字母进行保存
        for (i,c) in input.enumerated() {
            var index: Int // 来确定箱子的具体位置,也就是箱子在第几行
            if (i/n%2 == 0) { // 偶数行
                index = i%n
            }else { // 奇数行
                index = n-1-i%n
            }
            if mapDic.keys.contains(index) {
                let temp = mapDic[index]!
                mapDic.updateValue(temp.appending(String(c)), forKey: index)
            }else {
                mapDic.updateValue(String(c), forKey: index)
            }
        }
        for (_, v) in mapDic.sorted(by: <) {
            print(v)
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容