题目:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例:
输入: haystack = "hello", needle = "ll"
输出: 2
代码:
public class Test14 {
@Test
public void test(){
String haystack = "hello";
String needle = "ll";
System.out.println(new Test14().strStr(haystack, needle));
}
public int strStr(String haystack, String needle) {
if (needle=="") {
return 0;
}
char[] chars = haystack.toCharArray();
char[] chars1 = needle.toCharArray();
for (int i = 0; i <=chars.length-needle.length(); i++) {
int result = 0;
int j = i;
for (int i1 = 0; i1 < chars1.length; i1++) {
if (chars[j]==chars1[i1]) {
j++;
result++;
}else{
break;
}
}
if (result==chars1.length) {
return i;
}
}
return -1;
}
}