题目来源:字符串查找
题目描述:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例:
如果 source = “source” 和 target = “target”,返回 -1。
如果 source = “abcdabcdefg” 和 target = “bcd”,返回 1。
Java代码:
public int strStr(String source, String target) {
//write your code here
if (source==null&&target==null) {
return -1;
}else if (source!=null&&target==null) {
return -1;
}else if (source==null&&target!=null) {
return -1;
}
char[] sourcearray = source.toCharArray();
char[] targetarray = target.toCharArray();
if (source.length()==0&&target.length()==0) {
return 0;
}else if (source.length()!=0&&target.length()==0) {
return 0;
}else if (source.length()==0&&target.length()!=0) {
return -1;
}
int k = 0;
for (int i = 0; i < sourcearray.length; i++) {
if (sourcearray[i] == targetarray[0]) {
k = 0;
for (int j = i; j < targetarray.length+i&&k < targetarray.length; j++) {
if (sourcearray[j] == targetarray[k]) {
k++;
}
}
if (k == targetarray.length) {
return i;
}
}
}
return -1;
}