实现strStr()功能
题:找出目标字符串在原字符串首次出现的位置
Input: haystack = “hello”, needle = “ll”
Output: 2
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
【注】:当目标字符串是空时,应该返回什么呢,这是一个非常适合在面试中问到的问题。本题中当目标字符串是空时,返回0,这与C语言中的strstr()和java中的indexOf()是一致的。
思路:第一想法还是暴力破解,发现自己没得救了,数据结构的知识得恶补一下,这道题用KMP算法会更加的好。(要熟练掌握)
代码:
class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle == ""){
return 0;
}
char[] t = haystack.toCharArray();
char[] p = needle.toCharArray();
int i = 0;
int j = 0;
while(i < t.length && j < p.length) {
if(t[i] == p[j]){
i++;
j++;
}
else{
i = i - j + 1;
j = 0;
}
}
if(j == p.length) {
return i - j;
}
else{
return -1;
}
}
}
基于这道题,我找了一下对KMP算法详细讲解的帖子,很详细。
https://www.cnblogs.com/yjiyjige/p/3263858.html