OR174. 实现字通配符*
描述
在Linux Shell命令下通配符'*'表示0个或多个字符, 现编写一段代码实现通配符'*'的功能,注意只需要实现'*', 不用实现其他通配符。输入描述
第一行输入通配字符串输出描述
输出所有匹配的字串起始位置和长度,每行一个匹配输出示例1
输入:
shopee*.com shopeemobile.com
输出:
0 16
说明:
0 起始位置,16长度示例2
输入:
*.com shopeemobile.com
输出:
0 16 1 15 2 14 3 13 4 12 5 11 6 10 7 9 8 8 9 7 10 6 11 5 12 4
示例3
输入:
o*m shopeemobile.com
输出:
2 5 2 14 7 9 14 2
Go 解法, 执行用时: 4ms, 内存消耗: 996KB, 提交时间: 2020-06-01
package main import ( "bufio" "fmt" "os" "sort" "strconv" ) var memo map[int]int = map[int]int{} var s,t string func main(){ scanner := bufio.NewScanner(os.Stdin) scanner.Scan() s = scanner.Text() scanner.Scan() t = scanner.Text() lenT := len(t) var flag bool = false for i := 0;i < lenT;i++{ if s[0] == t[i] || s[0] == '*'{ Dfs(i,0) } arr := make([]int,len(memo)) var m int = 0 for k,_ := range memo{ delete(memo,k) if k != i{ flag = true } arr[m] = k m++ } sort.Ints(arr) for j := 0;j < m;j++{ if arr[j] == i{ continue } fmt.Println(strconv.Itoa(i) + " "+ strconv.Itoa(arr[j]-i)) } } if flag == false{ fmt.Println("-1 0") } } func Dfs(i,j int){ if j == len(s){ memo[i]++ return } if i == len(t){ return } if s[j] == t[i]{ Dfs(i+1,j+1) }else if s[j] == '*'{ Dfs(i+1,j) Dfs(i,j+1) Dfs(i+1,j+1) } return }
Go 解法, 执行用时: 5ms, 内存消耗: 1232KB, 提交时间: 2020-06-29
package main import ( "bufio" "fmt" "os" "sort" "strconv" ) var memo map[int]int = map[int]int{} var s,t string func main(){ scanner := bufio.NewScanner(os.Stdin) scanner.Scan() s = scanner.Text() scanner.Scan() t = scanner.Text() lenT := len(t) var flag bool = false for i := 0;i < lenT;i++{ if s[0] == t[i] || s[0] == '*'{ Dfs(i,0) } arr := make([]int,len(memo)) var m int = 0 for k,_ := range memo{ delete(memo,k) if k != i{ flag = true } arr[m] = k m++ } sort.Ints(arr) for j := 0;j < m;j++{ if arr[j] == i{ continue } fmt.Println(strconv.Itoa(i) + " "+ strconv.Itoa(arr[j]-i)) } } if flag == false{ fmt.Println("-1 0") } } func Dfs(i,j int){ if j == len(s){ memo[i]++ return } if i == len(t){ return } if s[j] == t[i]{ Dfs(i+1,j+1) }else if s[j] == '*'{ Dfs(i+1,j) Dfs(i,j+1) Dfs(i+1,j+1) } return }