[leetcode]28. Implement strStr()实现strStr()

时间:2024-08-26 08:05:19

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

题意:

实现strStr() : Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

Solution1:Two Pointers, finding substring[i...j] in str1,such that it equals str2

[leetcode]28. Implement strStr()实现strStr()

code:

 /*
Time: O(n^2).
Space: O(1).
*/ class Solution {
public int strStr(String s1, String s2) {
//题意确认 return 0 when needle is an empty string
if(s2.length() == 0) return 0; //for(int i = 0; i < s1.length(); i++){ 确保s1中含有s2,则扫s1的指针的范围可以缩小到s1.length() - s2.length() + 1
for(int i = 0; i < s1.length() - s2.length() + 1; i++){
int j = i;
int k = 0;
while( j < s1.length() && k < s2.length() && s1.charAt(j) == s2.charAt(k)){
j++;
k++;
}
if( k == s2.length()){
return i;
}
}
return -1;
}
}