MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / IsInterleave

Function IsInterleave

dynamic/interleavingstrings.go:10–36  ·  view source on GitHub ↗

IsInterleave checks if string `s1` and `s2` can be interleaved to form string `s3`

(s1, s2, s3 string)

Source from the content-addressed store, hash-verified

8
9// IsInterleave checks if string `s1` and `s2` can be interleaved to form string `s3`
10func IsInterleave(s1, s2, s3 string) bool {
11 if len(s1)+len(s2) != len(s3) {
12 return false
13 }
14
15 dp := make([][]bool, len(s1)+1)
16 for i := range dp {
17 dp[i] = make([]bool, len(s2)+1)
18 }
19
20 dp[0][0] = true
21 for i := 1; i <= len(s1); i++ {
22 dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
23 }
24
25 for j := 1; j <= len(s2); j++ {
26 dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]
27 }
28
29 for i := 1; i <= len(s1); i++ {
30 for j := 1; j <= len(s2); j++ {
31 dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
32 }
33 }
34
35 return dp[len(s1)][len(s2)]
36}

Callers 1

TestIsInterleaveFunction · 0.92

Calls

no outgoing calls

Tested by 1

TestIsInterleaveFunction · 0.74