题目描述:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路解析:
- 遍历给出的haystack字符串,如果剩下的长度小于needle的长度,返回null
- 如果找到一致的单字符,就循环遍历,直到遍历的长度为needle的长度为止
代码:
public class Solution {
public String strStr(String haystack, String needle) {
if(needle==null|| needle.length()==0)
return haystack;
for(int i=0;i<haystack.length();i++){
if(haystack.length()-i<needle.length())
return null;
int k=i;
int j=0;
while(k<haystack.length() && j<needle.length() && haystack.charAt(k)==needle.charAt(j)){
k++;
j++;
if(j==needle.length())
return haystack.substring(i);
}
}
return null;
}
}