您的位置:首页 > 其它

leetcode 28. Implement strStr()

2016-05-16 14:31 381 查看
原题链接:28. Implement strStr()
【思路】

用 i 表示 haystack 的索引,每次对于 i,用 count 记录匹配到的最大长度,如果 count = needle 的长度,则返回 true,否则 i+1,再次进行匹配,如果都没找到,则返回 false:

public int strStr(String haystack, String needle) {
int len1 = haystack.length(), len2 = needle.length();
for (int i = 0; i < len1 - len2 + 1; i++) {
int count = 0;
while (count < len2 && haystack.charAt(i + count) == needle.charAt(count)) count++;
if (count == len2) return i;
}
return -1;
}
72 / 72 test
cases passed. Runtime: 3
ms Your runtime beats 59.00% of javasubmissions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: