题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
有一个方法,参数为两个字符串,返回第二个参数第一次在第一个参数中出现的坐标。
首先,判断是否为null,为空那没的说,返回-1;
其次,判断是否为空字符串,如果两者皆为空字符串,返回0
最后,是统一处理普通情况的字符串。
先转换为字符数组,
遍历第一个字符数组,其间嵌套遍历第二个字符数组,只有第二个字符数组的每一个元素都与第一个字符数组中相吻合,就返回index
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
int longStrLen = haystack.length();
int shortStrLen = needle.length();
if (shortStrLen > longStrLen) {
return -1;
}
if (shortStrLen == 0 && longStrLen ==0) {
return 0;
}
char[] longStr = haystack.toCharArray();
char[] shortStr = needle.toCharArray();
for (int index = 0; index < longStrLen; index++) {
int tempIndex = index;
for (int j = 0; j < shortStrLen; j++) {
if (shortStr[j] == longStr[tempIndex]) {
tempIndex++;
if (j == shortStrLen-1) {
return index;
}
if (tempIndex == longStrLen) {
return -1;
}
} else {
tempIndex = -1;
break;
}
}
if (tempIndex != -1) {
return index;
}
}
return -1;
}
}