Swift solution - Divide and Conquer


  • 0
    class Solution {
        func diffWaysToCompute(_ input: String) -> [Int] {
            let characters = Array(input.characters)
            var result = [Int]()
            
            for i in 0..<characters.count {
                if characters[i] == "-" || characters[i] == "*" || characters[i] == "+" {
                    let part1 = String(characters[0...(i - 1)])
                    let part2 = String(characters[(i + 1)...(characters.count - 1)])
                    let part1Result = diffWaysToCompute(part1)
                    let part2Result = diffWaysToCompute(part2)
                    for p1 in part1Result {
                        for p2 in part2Result {
                            var sum = 0
                            if characters[i] == "+" {
                                sum = p1 + p2
                            } else if characters[i] == "-" {
                                sum = p1 - p2
                            } else if characters[i] == "*" {
                                sum = p1 * p2
                            }
                            result.append(sum)
                        }
                    }
                }
            }
            
            return result.count == 0 ? [Int(input)!] : result
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.