Monday, January 20, 2014

Implement strStr(). Java

LeetCode


Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.


/*
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack,
or null if needle is not part of haystack.
*/
public class StrStr {
public String strStr(String haystack, String needle) {
if (haystack==null||needle==null){
return null;
}
if (haystack.length()==0){
if (needle.length()==0){
return haystack;
}
else{
return null;
}
}
if (needle.length()==0){
return haystack;
}
if (haystack.length()<needle.length()){
return null;
}
// below code is a modified version of code in /**/ below, idea from a google+ friend.
if (i>=0){
return haystack.substring(i);
}
else{
return null;
}
/*
int i=0;
int len=haystack.length()-needle.length();
while(i<=len){
if (haystack.charAt(i)==needle.charAt(0)){
if (haystack.substring(i, i+needle.length()).equals(needle)){
return haystack.substring(i);
}
}
i++;
}
return null;
*/
}
}
// without use substring()
public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function
assert(haystack!=null && needle!=null);
if (needle.length()==0){
return haystack;
}
int i=0;
while (i<haystack.length()){
if (haystack.length()-i<needle.length()){
break;
}
if (haystack.charAt(i)==needle.charAt(0)){
int j=i;
while (j-i<needle.length()&&needle.charAt(j-i)==haystack.charAt(j)){
j++;
if (j-i==needle.length()){
return haystack.substring(i);
}
}
}
i++;
}
return null;
}
}
view raw StrStr.java hosted with ❤ by GitHub

No comments:

Post a Comment