Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
No comments:
Post a Comment