Last active
August 29, 2015 13:56
-
-
Save Jeffwan/8891523 to your computer and use it in GitHub Desktop.
Implement strStr() @leetcode
This file contains hidden or 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment