Swift solusion


  • 0
    M
    class Solution {
        func wordPattern(_ pattern: String, _ str: String) -> Bool {
            var map : Dictionary<Character, String> = [:]
            var map2 : Dictionary<String, Character> = [:]
            
            var arr = str.split(separator: " ")
            
            if pattern.characters.count != arr.count {
                return false
            }
            
            for (i,c) in pattern.characters.enumerated() {
                if let value = map[c] {
                    if value != arr[i] {
                        return false
                    }
                }
                
                if let value = map2[String(arr[i])] {
                    if value != c {
                        return false
                    }
                }
                
                map.updateValue(String(arr[i]), forKey: c)
                map2.updateValue(c, forKey: String(arr[i]))
            }
            return true
        }
    }
    

Log in to reply
 

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