问题链接
Implement strStr() | LeetCode OJ
问题描述
实现字符串查找函数,给出两个字符串haystack
和needle
,返回needle
在haystack
中的第一次出现的位置,不存在则返回-1。
解决办法
public class Solution {
public int strStr(String haystack, String needle) {
int haystackLength = haystack.length();
int needleLength = needle.length();
if(haystackLength == 0 && needleLength == 0){
return 0;
}
else if(haystackLength == 0){
return -1;
}
else if(needleLength == 0){
return 0;
}
else if(haystackLength < needleLength){
return -1;
}
int startPosition = haystackLength - needleLength;
for (int i = 0; i <= startPosition; i++) {
boolean same = true;
for (int j = 0; j < needleLength; j++) {
char a = haystack.charAt(i + j);
char b = needle.charAt(j);
if (a != b) {
same = false;
break;
}
}
if (same) {
return i;
}
}
return -1;
}
}