在 Swift 中使用 enum 实现状态机

在 Swift 中使用 enum 实现状态机

LeetCode 91. Decode Ways 的暴力解法。

  此代码为 LeetCode 91. Decode Ways 的暴力解法。使用一个状态机表示当前解码状态,每个状态下允许的字符列表不同,能够产生的新状态也不同。当处理完所有字符后解码完成。

class Solution {
    enum DecodeState {
        /// 1~9
        case zero(Substring)
        /// 10~19
        case one(Substring)
        /// 20~26
        case two(Substring)
        
        func next() -> [DecodeState] {
            switch self {
            case .zero(let substring):
                if let c = substring.first {
                    let next = substring.index(after: substring.startIndex)
                    switch c {
                    case "1":
                        return [.zero(substring[next...]), .one(substring[next...])]
                    case "2":
                        return [.zero(substring[next...]), .two(substring[next...])]
                    case "3", "4", "5", "6", "7", "8", "9":
                        return [.zero(substring[next...])]
                    default:
                        return []
                    }
                } else {
                    return []
                }
            case .one(let substring):
                if let c = substring.first {
                    let next = substring.index(after: substring.startIndex)
                    switch c {
                    case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
                        return [.zero(substring[next...])]
                    default:
                        return []
                    }
                } else {
                    return []
                }
            case .two(let substring):
                if let c = substring.first {
                    let next = substring.index(after: substring.startIndex)
                    switch c {
                    case "0", "1", "2", "3", "4", "5", "6":
                        return [.zero(substring[next...])]
                    default:
                        return []
                    }
                } else {
                    return []
                }
            }
        }
    }
    
    func numDecodings(_ s: String) -> Int {
        var count = 0
        var states: [DecodeState] = [.zero(s[...])]
        while let state = states.popLast() {
            switch state {
            case .zero(let substring):
                if substring.isEmpty {
                    count += 1
                } else {
                    states.append(contentsOf: state.next())
                }
            default:
                states.append(contentsOf: state.next())
            }
        }
        return count
    }
}

修订记录

2022-10-08T15:00:13+08:00