Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
笨方法1:
class Solution { public int strStr(String haystack, String needle) { if(needle==""||needle==null){ return 0; } else return haystack.indexOf(needle); } }
直接用indexOf
方法2:
class Solution { public int strStr(String haystack, String needle) { if (needle.isEmpty()) return 0; int m = haystack.length(); int n = needle.length(); if (n > m) return -1; for (int i = 0; i <= m - n; i++) { int j = 0; for (; j < n; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) break; } if (j == n) return i; } return -1; } }