• + 0 comments

    swift using built in regex

    func gridSearch(G: [String], P: [String]) -> String {
        // Write your code here
        
        var pIndex: Int = 0
        var gIndex: Int = 0
        var prevIndex: Int = -1
        
        var set = Set<Character>()
        
        while(gIndex <= G.count - 1) {
            if let ranged = G[gIndex].range(of: P[pIndex], options: .regularExpression) {
                let index: Int = G[gIndex].distance(from: G[gIndex].startIndex, to: ranged.lowerBound)
                       
                if prevIndex != -1 && prevIndex != index { 
                    let squeezed: String = G[gIndex - 1].filter{ set.insert($0).inserted }
                    if squeezed.count != 1 {
                        pIndex = 0
                        prevIndex = -1
                        continue
                    }
                 }
                if pIndex == P.count - 1 { break } 
                if pIndex < P.count - 1 { pIndex += 1 } 
                if prevIndex == -1 { prevIndex = index }
                
            } else if (pIndex != 0) {
                pIndex = 0 
                continue 
            }
    
            gIndex += 1
        }
            
        return pIndex == P.count - 1 ? "YES" : "NO"
    }