arrays - 如何在 Swift 中的方向数组缩减挑战中正确实现堆栈

标签 arrays swift algorithm stack lifo

我正在尝试解决 Swift 中的编码挑战。任务是构建一个接受一系列方向的函数,例如:["NORTH", "WEST", "EAST", "NORTH", "EAST", "SOUTH"] .应删除阵列中彼此相邻的任何相反方向。使用上面的示例,应该删除第二个和第三个索引(“WEST”和“EAST”)。但是,最后一个索引“SOUTH”应该保留,因为它不直接紧邻数组中的“NORTH”值。

我正在尝试实现一个堆栈以比较这些值,但无法使其正常工作。这是我第一次实现堆栈,而且我仍然在习惯 Swift 语法。

我的代码是这样设置的:

struct StringStack {
    var array: [String] = []

    func peek() -> String {
        guard let topElement = array.first else { fatalError("The Stack is empty.")}
        return topElement
    }

    mutating func pop() -> String {
        return array.removeFirst()
    }

    mutating func push(_ element: String) {
        array.insert(element, at: 0)
    }
}

func directionsReduce(_ directions: [String]) -> [String] {
    var reducedDirs = StringStack()

    reducedDirs.push(directions[1])
    for direction in directions {
        if((direction == "NORTH" && reducedDirs.peek() == "SOUTH")
            || (direction == "SOUTH" && reducedDirs.peek() == "NORTH")
            || (direction == "EAST" && reducedDirs.peek() == "WEST")
            || (direction == "WEST" && reducedDirs.peek() == "EAST")
        ) {
            reducedDirs.pop()
        } else {
            reducedDirs.push(direction)
        }
    }

    return reducedDirs.array
}

let testDirections1 = ["WEST", "WEST", "NORTH", "SOUTH", "EAST", "WEST"]
print(directionsReduce(testDirections1))

我所拥有的返回一个数组 ["WEST", "WEST", "WEST"] ,但是,这应该返回 ["WEST", "WEST"] .我不确定如何初始化堆栈以解决此问题。我很感激任何可以看一看的新鲜眼睛。我也很好奇这是否是实现堆栈的最佳实践,或者是否有更好的方法来应对这一挑战。感谢任何帮助或建议。

最佳答案

对于列表中的其余元素(方向 [1:]),将元素添加到堆栈 如果堆栈为空 如果peek的结果和元素不是相反的方向 .否则,弹出堆栈顶部的元素并继续下一个。

大小/长度方法对您的堆栈实现很有用。它会在 peek() 之前提供支票防止抛出 fatalError

func directionsReduce(_ directions: [String]) -> [String] {
    var reducedDirs = StringStack()

    reducedDirs.push(directions[0])
    for direction in directions[1...] {
        if ((reducedDirs.length() == 0) 
             || (!areOppositeDirections(direction, reducedDirs.peek()))
        {
            reducedDirs.push(direction)
        } else {
            reducedDirs.pop()
        }
    }

    return reducedDirs.array
}

let testDirections1 = ["WEST", "WEST", "NORTH", "SOUTH", "EAST", "WEST"]
print(directionsReduce(testDirections1))

关于arrays - 如何在 Swift 中的方向数组缩减挑战中正确实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066397/

相关文章:

c - 查找 C 语言中最长的单词

c - 有什么方法可以在 C 中使用具有常量索引的常量数组作为 switch case 标签?

ios - 如何在 Swift 中进行弱链接?

swift - 已经声明的变量显示 'variable used before declaration'

python - 在 python 中计算列表中的字符串然后过滤和匹配

python - 如何根据另一列替换 numpy 数组中的值?

c - 在 C 中使用数组进行扫描和求和

ios - 如何快速将json传递给服务器

c++ - 邻接表中的深度优先或广度算法

python - 使用 t-SNE 降维执行聚类