-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepeated-substring-pattern.go
More file actions
72 lines (61 loc) · 1.54 KB
/
repeated-substring-pattern.go
File metadata and controls
72 lines (61 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
)
// source: https://leetcode.com/problems/repeated-substring-pattern/
// First find all possible substring lengths by getting all dividers of the len(s) but len(s)
// Then for all of them check if repeating substr of these lengths
// going to create a string equal to the source one
func repeatedSubstringPattern(s string) bool {
if len(s) == 1 {
return false
}
possibleSubstrLengths := getDivisors(len(s))
for _, psl := range possibleSubstrLengths {
ss := s[:psl]
ok := true
for i := 0; i < len(s)/psl; i++ {
if s[i*psl:(i+1)*psl] != ss {
ok = false
break
}
}
if ok {
return true
}
}
return false
}
func getDivisors(n int) []int {
var res []int
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if n/i != i && i != 1 {
res = append(res, i, n/i)
} else {
res = append(res, i)
}
}
}
return res
}
func main() {
//// Example 1
//var s1 string = "abab"
//fmt.Println("Expected: true Output: ", repeatedSubstringPattern(s1))
// Example 2
var s2 string = "aba"
fmt.Println("Expected: false Output: ", repeatedSubstringPattern(s2))
// Example 3
var s3 string = "abcabcabcabc"
fmt.Println("Expected: true Output: ", repeatedSubstringPattern(s3))
// Example 4
var s4 string = "a"
fmt.Println("Expected: false Output: ", repeatedSubstringPattern(s4))
// Example 5
var s5 string = "aaaaaaaaaaaaa"
fmt.Println("Expected: true Output: ", repeatedSubstringPattern(s5))
// Example 6
var s6 string = "bb"
fmt.Println("Expected: true Output: ", repeatedSubstringPattern(s6))
}