Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Solution:
We should consider it in C, since it mentioned pointer.
Returns a pointer in C is equal to return the rest of String in Java.
Solution:
We should consider it in C, since it mentioned pointer.
Returns a pointer in C is equal to return the rest of String in Java.
// pointer???? --> substring of haystack
public class Solution {
public String strStr(String haystack, String needle) {
int m = haystack.length();
int n = needle.length();
if(n == 0)
return haystack;
for(int i = 0; i <= m - n; i++){
if(haystack.charAt(i) == needle.charAt(0)){
int j = i;
int k = 0;
while(j < m && k < n && haystack.charAt(j) == needle.charAt(k)){
j++;
k++;
}
if(k == n)
return haystack.substring(i);
}
}
return null;
}
}

No comments:
Post a Comment