Created
February 6, 2021 11:19
-
-
Save asatake/98145575a0638e250bdb781f2eeb0a8f to your computer and use it in GitHub Desktop.
quick search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
) | |
const SIGMA = 256 | |
func native(ts, ps []string) { | |
n := len(ts) | |
m := len(ps) | |
if n == 0 || m == 0 { | |
return | |
} | |
for i := 0; i <= n-m; i++ { | |
j := 0 | |
for j = 0; j < m && ps[j] == ts[i+j]; { | |
j++ | |
} | |
if j == m { | |
fmt.Println(i) | |
} | |
} | |
} | |
func quickSearch(ts, ps []string) { | |
n := len(ts) | |
m := len(ps) | |
if n == 0 || m == 0 { | |
return | |
} | |
// 要素数+1を参照するため | |
ts = append(ts, "") | |
// 移動表 | |
shift := make(map[string]int) | |
for i := 0; i < m; i++ { | |
shift[ps[i]] = m - i | |
} | |
for i := 0; i <= n-m; { | |
j := 0 | |
for j = 0; j < m && ps[j] == ts[i+j]; j++ { | |
} | |
if j == m { | |
fmt.Println(i) | |
} | |
if shift[ts[i+m]] != 0 { | |
i += shift[ts[i+m]] | |
} else { | |
i += m | |
} | |
} | |
} | |
func main() { | |
var t, p string | |
var sc = bufio.NewScanner(os.Stdin) | |
if sc.Scan() { | |
t = sc.Text() | |
} | |
if sc.Scan() { | |
p = sc.Text() | |
} | |
ts := strings.Split(t, "") | |
ps := strings.Split(p, "") | |
fmt.Println("===== NATIVE =====") | |
native(ts, ps) | |
fmt.Println("===== QS =====") | |
quickSearch(ts, ps) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment