Swift solution using two dictionary, easy understand code


  • 0
        func wordPattern(pattern: String, _ str: String) -> Bool {
        if str == "" || pattern == "" {
            return false
        }
        
        let letters = [Character](pattern.characters)
        let words = str.componentsSeparatedByString(" ")
        
        if letters.count != words.count {
            return false
        }
        
        var letterMapWord = [Character : String]()
        var wordMapLetter = [String : Character]()
        
        for index in 0 ..< letters.count {
            let letter = letters[index]
            let word = words[index]
            
            let cachedWord = letterMapWord[letter]
            let cachedLetter = wordMapLetter[word]
            if cachedWord == nil && cachedLetter == nil {
                letterMapWord[letter] = word
                wordMapLetter[word] = letter
            } else if letter != cachedLetter || word != cachedWord {
                return false
            }
        }
        
        return true
    
        }
    

Log in to reply
 

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