Monday, February 10, 2014

Implement strStr() @LeetCode


Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
package leetcode.simpleCoding;
/**
* @date Feb 8, 2014
*
* Test case: (1123 123) ("","") --> may OutOfBound ,("a","a") --> s1.length()- s2.length()+1 not without +1, bound check.
* return value: haystack.subString(i) but not String.valueOf(i) ("","" will return 0).
* take care
*/
public class StrStr {
public static void main(String args[]) {
String haystack = "a";
String needle = "a";
System.out.println(strStr(haystack, needle));
}
public static String strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return null;
}
int i,j = 0;
for (i = 0; i < haystack.length() - needle.length() + 1; i++) {
for (j = 0; j<needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return haystack.substring(i);
}
}
return null;
}
}
view raw StrStr.java hosted with ❤ by GitHub

No comments:

Post a Comment