Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
//方法1:最常规的解法,两个while循环依次比较,时间复杂度为O(n*n),运行时间为608ms!!!
public class Solution {
public int strStr(String haystack, String needle) {
char hay[] = haystack.toCharArray();
char need[] = needle.toCharArray();
int lenh = hay.length;
int lenn = need.length;
int i = 0;
int j = 0;
int temp = 0;
if ((lenh == 0 && lenn == 0) || (lenn == 0)){
return 0;
}
if (lenh == 0 || (lenh < lenn)){
return -1;
}
if ((lenh == lenn) && (hay[0] != need[0])){
return -1;
}
while (i < lenh){
while ((i < lenh) && (hay[i] != need[j])){
i ++;
}
if (i == lenh){
return -1;
}
temp = i;
while ((i < lenh) && (j < lenn) && (hay[i] == need[j])){
i ++;
j ++;
}
if (j == lenn){
return temp;
}
else {
i = temp + 1;
j = 0;
}
}
return -1;
}
}
由于方法1的runtime实在太吓人了,所以必须有更优化的方法才对。每一次比较的时候都要先考察needle的首字母x,如果haystack里有不止一个x时,可以考虑将所有x存在的位置保存在一个数组里,这样每次就可以直接从x开始比较,更加节省时间。
//用k表示needle的首字母在haystack中出现的次数,n表示needle的长度,则时间复杂度为O(k*n),运行时间256ms
public class Solution {
public int strStr(String haystack, String needle) {
char hay[] = haystack.toCharArray();
char need[] = needle.toCharArray();
int lenh = hay.length;
int lenn = need.length;
if ((lenh == 1 && lenn == 1) || (lenh == 0 && lenn == 0) || (lenn == 0)){
return 0;
}
if (lenh == 0 || (lenh < lenn)){
return -1;
}
if ((lenh == lenn) && (hay[0] != need[0])){
return -1;
}
int i = 0;
int j = 0;
int k = 0;
int arr[] = new int[lenh];
for (i = 0; i < lenh; i ++){
arr[i] = -1;
} //用数组arr[]保存好每一个needle的首字母出现的位置
i = 0;
while (i < lenh){
if (hay[i] == need[j]){
arr[k] = i;
k ++;
}
i ++;
}
for (i = 0; arr[i] != -1; i ++){ //直接从每一个首字母开始查询比较
j = arr[i];
k = 0;
while ((j < lenh) && (k < lenn) && (hay[j] == need[k])){
j ++;
k ++;
}
if (k == lenn){
return arr[i];
}
if (j == lenh){
return -1;
}
}
return -1;
}
}
想尝试一下用二维数组arr[ ]保存,行表示haystack数组,列表示needle数组,arr[ i ][ j ]为0或1分别表示行与列的元素相等与否,当arr[ i ][ needle长度 - 1 ] == 1时,即满足条件,但是程序在leetcode运行时出现 Memory Limit Exceeded 错误,暂时还没能找到解决方法,待续。。。
public class Solution {
public int strStr(String haystack, String needle) {
char hay[] = haystack.toCharArray();
char need[] = needle.toCharArray();
int lenh = hay.length;
int lenn = need.length;
if ((lenh == 1 && lenn == 1) || (lenh == 0 && lenn == 0) || (lenn == 0)){
return 0;
}
if (lenh == 0 || (lenh < lenn)){
return -1;
}
if ((lenh == lenn) && (hay[0] != need[0])){
return -1;
}
int i = 0;
int j = 0;
int p;
int arr[][] = new int[lenh][lenn];
while (i < lenh){
p = i;
while ((i < lenh) && (j < lenn)){
if (hay[i] != need[j]){ //行列相等置为1,不等置为0
break;
}
else {
arr[i][j] = 1;
i ++;
j ++;
while ((i < lenh) && (j < lenn) &&(hay[i] == need[j])){
arr[i][j] = arr[i - 1][j - 1] + 1;
i ++;
j ++;
}
if (arr[i - 1][j - 1] == lenn){
return p;
}
}
j = 0;
}
i = p;
i ++;
}
return -1;
}
}