Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.題目要求咱們實現strStr方法。就是在一個長字符串中是否包含咱們所輸入的子字符串。若是存在,返回子字符串的在長字符串的起始點的位置。若是不存在,則返回-1。code
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1字符串
public int strStr(String haystack, String needle) { int l1 = haystack.length(), l2 = needle.length(); if(l1 < l2)return -1; if(l2 == 0)return 0; for(int i=0;i<l1-l2+1;i++){ if (haystack.substring(i,i+l2).equals(needle)) { return i; } } return -1; }