Skip to content

Instantly share code, notes, and snippets.

@Jeffwan
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save Jeffwan/8891523 to your computer and use it in GitHub Desktop.

Select an option

Save Jeffwan/8891523 to your computer and use it in GitHub Desktop.
Implement strStr() @leetcode
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment