하루에 하나의 자바 필기 시험 2020-9-23
LeetCode : 28. strStr () 구현
strStr () 함수를 구현하십시오.
건초 더미 줄과 바늘 줄이 주어지면 건초 더미 줄에서 바늘 줄이 나타나는 첫 번째 위치 (0부터 시작)를 찾습니다. 존재하지 않으면 -1 이 반환 됩니다.
예 1 :
输入: haystack = "hello", needle = "ll"
输出: 2
예 2 :
输入: haystack = "aaaaa", needle = "bba"
输出: -1
기술:
하면 needle
빈 문자열, 우리가해야 할 일의 반환 값은? 이것은 인터뷰에서 좋은 질문입니다.
이 문제의 경우 needle
0을 반환해야 할 때 빈 문자열 이 발생 합니다. 이것은 C 언어의 strstr () 및 Java의 indexOf () 정의와 일치합니다.
이중 포인터 방법 :
package cn.lbl.face.leetCode;
public class 实现strStr {
public static int strStr(String haystack, String needle) {
//如果needle是空字符串时,返回0
if (needle == null || needle.length()==0) {
return 0;
}
int i=0;
while (i<needle.length()) {
int index = haystack.indexOf(needle, i);
if (index == -1) {
return index;
}
i = index;
for (int j = 0; j < needle.length(); j++, index++) {
if (haystack.charAt(index) != needle.charAt(j)) {
break;
}
}
return i;
}
return -1;
}
public static void main(String[] args) {
System.out.println(strStr("aaaaa","bba"));
}
}