實(shí)現(xiàn) strStr() 函數(shù)。給定一個(gè) haystack 字符串和一個(gè) needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個(gè)位置 (從0開始)。如果不存在,則返回 -1。
示例 :輸入: haystack = "hello", needle = "ll",輸出: 2
鏈接:https://leetcode-cn.com/problems/implement-strstr
①如果子串needle為空,按照C++中的strstr()和Java中的indexOf()方法中的定義,應(yīng)該返回0
②如果子串長(zhǎng)度大于字符串haystack的長(zhǎng)度,顯然不可能找到這樣的子串位置
③從頭開始逐一遍歷,利用Java中的substring()方法、equals()方法可以很容易找到
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0) return 0;//子串為空,返回0
if(haystack.length()<needle.length()) return -1;//haystack長(zhǎng)度比子串小,不可能找得到
int res=0,i=0;
for(i=0;i<=haystack.length()-needle.length();i++){//遍歷原字符串,逐一比較
if(haystack.substring(i,i+needle.length()).equals(needle)) return i;
}
return -1;
}
}