Swift Solution: Where can I improve?


  • 0
    T

    Xcode Playground-friendly.

    func getHint(secret: String, guess: String) -> String
    {
        var bulls = 0   // A
        var cows = 0    // B
        var bullChars = [Character]()
    
        var secretIndex = secret.startIndex
        for digit in guess.characters
        {
            if digit == secret[secretIndex]
            {
                bullChars.append(digit)
                bulls++
            }
            else if !bullChars.contains(digit)
            {
                cows++
            }
            secretIndex++
        }
    
        return "\(bulls)A\(cows)B"
    }
    
    getHint("1807", guess: "7810") // "1A3B"
    getHint("1123", guess: "0111") // "1A1B"
    getHint("0111", guess: "0111") // "4A0B"

Log in to reply
 

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