Leetcode 28, Strstr

//思路:双指针,因为两个string肯定二个循环。遍历整个长字符(减去短字符)作为起点,双指针长字符和短字符逐一比较。

//答案综合https://leetcode.com/discuss/95153/java-easy-to-understand-solutions(双指针比较清晰)和爱做饭第一个(答案返回string过时了,

//第二个没必要)。

public int strStr(String haystack, String needle) {
	if (haystack == null || needle == null)
		return -1;
	for (int i = 0; i <= haystack.length() - needle.length(); i++) {
		int hayPointer = i;
		int needlePointer = 0;
		while (needlePointer < needle.length() && haystack.charAt(hayPointer) == needle.charAt(needlePointer)) {
			hayPointer++;
			needlePointer++;
		}
		if (needlePointer == needle.length()){
			return i;
		}
	}
	return -1;
}



阅读更多
个人分类: 个人观点
上一篇oracle创建表空间,创建用户(转)
下一篇Leetcode 38,Count and say
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭