代码拉取完成,页面将自动刷新
package code;
/*
* 28. Implement strStr()
* 题意:找出子串在给定字符串的起始位置
* 难度:Easy
* 分类:Two Pointers, String
* Tips:注意判断子串为空的方法为needle.length()==0,不要用needle==""
* 最优的解法应该是O(N)的,类似KMP的思路,不过面试不会让写KMP的
*/
public class lc28 {
public static void main(String[] args) {
String haystack = "aaaaa";
String needle = "ab";
System.out.println(strStr(haystack, needle));
}
public static int strStr(String haystack, String needle) {
if(needle.length()==0)
return 0;
int cur1 = 0, cur2 = 0;
while(cur1<haystack.length()){
if(haystack.charAt(cur1)==needle.charAt(cur2)){
cur1++;
cur2++;
if(cur2==needle.length())
return cur1-cur2;
}else{
cur1++;
cur1 = cur1-cur2;
cur2 = 0;
}
}
return -1;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。