• + 0 comments

    Golang:

    func findMultipleIndexes(str, substr string) []int {
        var indices []int
        start := 0
        for {
            index := strings.Index(str[start:], substr)
            if index == -1 {
                break
            }
            indices = append(indices, start+index)
            start += index + 1
        }
        return indices
    }
    func Contains(M []int, Item int) bool{
        for _,v  := range M {
            if v == Item {
                return true
            }
        }
        
        return false
    }
    func gridSearch(G []string, P []string) string {
        // Write your code here
        const NO = "NO"
        const YES = "YES"
    
        if len(P) == 0 {
            return "NO"
        }
    
        row := -1
        // find the first line of patter match
        for i, v := range G {
            cols := findMultipleIndexes(v, P[0])
            for _, col := range cols {
                row = i
                // if next not lines available at the Group
                if row == -1 || col == -1 || len(G) < row+len(P) {
    
                    // return NO
                    continue
                }
    
                found := true
                // now check for next lines
                for j := row + 1; j < row+len(P); j++ {
                    i := j - row
                    ncols := findMultipleIndexes(G[j], P[i])
                    if !Contains(ncols, col) {
                        found = false
                        break
                    }
                }
    
                if found {
                    return YES
                }
            }
        }
    
        return NO
    }