Swift Code using dictionary


  • 1
    L
    func wordPattern(pattern: String, str: String) -> Bool {
        
        // convert to two arrays
        let wordArray = str.componentsSeparatedByString(" ")
        let patternArray = pattern.characters.map { String($0) }
        
        if wordArray.count != patternArray.count {
            return false
        }
        
        var dict = [String: String]()
    
        for (index, value) in patternArray.enumerate() {
            
            // dict has the pattern letter
            if dict.keys.contains(value) {
                if dict[value] != wordArray[index] {
                    return false
                }
            } else { // dict does not have this pattern letter
                if dict.values.contains(wordArray[index]) {
                    return false
                } else { // new pair of pattern letter and word, create in dict
                    dict[value] = wordArray[index]
                }
            }
        }
        return true
    }

Log in to reply
 

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