Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
public class Solution { public int strStr(String haystack, String needle) { // Brute-force substring search int n = haystack.length(); int m = needle.length(); for (int i = 0; i <= n-m; i++) { int j; for (j = 0; j < m; j++) if (haystack.charAt(i+j) != needle.charAt(j)) break; // Found if (j == m) return i; } // Not found return -1; } }
No comments:
Post a Comment