题目描述
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
输入: haystack = "hello", needle = "ll"
输出: 2
输入: haystack = "aaaaa", needle = "bba"
输出: -1
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
思路
- 两根指针
pH
/pN
, pH 指向haystack字符串, pN指向needle字符串 - 若
pH != pN
, 则pH继续向右移动 - 若
pH = pN
, pH / pN同时向右移动, 此时共同字符串长度+1, equalLen ++ - 若
equalLen == needle.length
,说明已找到目标位置
实现
public class A28 {
public static int strStr(String haystack, String needle) {
int hayStackLen = haystack.length();
int needleLen = needle.length();
if(needleLen == 0) {
return 0;
}
if(hayStackLen < needleLen) {
return -1;
}
int equalLen = 0;
int pH = 0;
int pN = 0;
while (pH < hayStackLen) {
if(haystack.charAt(pH) == needle.charAt(pN)) {
pH ++;
pN ++;
equalLen ++;
} else {
pN = 0;
// 回退字符串, 从第一个相等位置的下一个位置开始比较
pH = pH - equalLen + 1;
equalLen = 0;
}
if(needleLen == equalLen) {
return pH - equalLen;
}
}
return -1;
}
public static void main(String[] args) {
String haystack = "aabba", needle = "bba";
System.out.println(strStr(haystack, needle));
}
}