28. Implement strStr() java

Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

译文:返回字符串needle第一次出现在haystack的索引,或者如果needle不是haystack的一部分返回-1.

本题主要就是要熟悉String类的indexOf函数。

public class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}

String类的indexOf函数:

public int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring. 
The returned index is the smallest value k for which: 

 this.startsWith(str, k)
 
If no such value of k exists, then -1 is returned.
Parameters:
str - the substring to search for. 
Returns:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
点赞