Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 Sunday 匹配 精简版代码 #49

Open
dingweihua opened this issue Sep 13, 2021 · 0 comments
Open

实现 Sunday 匹配 精简版代码 #49

dingweihua opened this issue Sep 13, 2021 · 0 comments

Comments

@dingweihua
Copy link

dingweihua commented Sep 13, 2021

https://github.com/lifei6671/interview-go/blob/master/algorithm/docs/match-sunday-string.md

精简版代码供参考:

func strStrSunday(haystack, needle string) int {
	if haystack == "" {
		return -1
	}
	if needle == "" {
		return 0
	}

	haystackLen := len(haystack)
	needleLen := len(needle)
	i := 0
	for {
		// 先判断剩余字符串的长度是否足够
		if i+needleLen > haystackLen {
			return -1
		}
		// 匹配上之后,直接返回index
		if haystack[i:i+needleLen] == needle {
			return i
		}
		// 判断needle所在位置的下一个占位是否包含在haystack中
		// needle所在位置的下一个占位可能超出haystack的长度
		if i+needleLen == haystackLen {
			return -1
		}
		//lastIdx := strings.LastIndex(needle, string(haystack[i+needleLen]))
		lastIdx := -1
		for j := needleLen - 1; j >= 0; j-- {
			if haystack[i+needleLen] == needle[j] {
				lastIdx = j
				break
			}
		}
		// 根据lastIdx结果进行不同的移位
		if lastIdx >= 0 {
			i += needleLen - lastIdx
		} else {
			i += needleLen + 1
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant