题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例一:
输入: haystack = "hello", needle = "ll" 输出: 2
示例二:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
思路
1.既然是字符串的完全匹配,我们只需要将haystack分段进行截取,每段的截取内容和needle进行比较就可以了。
2.注意循环比较的次数应该等于haystack的长度减去needle的长度加一,这样就可以将每段都进行比较了。
Java代码实现
public int strStr(String haystack, String needle) {
int len = needle.length();
if(len == 0){
return 0;
}
for (int i = 0; i <= haystack.length()-len; i++) {
String cur = haystack.substring(i,i+len);
if(cur.equals(needle)){
return i;
}
}
return -1;
}Golang代码实现
func strStr(haystack string, needle string) int {
if len(needle) == 0{
return 0
}
hayLen := len(haystack)
needLen := len(needle)
for i:=0;i<hayLen-needLen+1;i++{
if haystack[i:i+needLen] == needle{
return i
}
}
return -1
}
京公网安备 11010502036488号