?LeetCode刷題實(shí)戰(zhàn)28:實(shí)現(xiàn) strStr()
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?實(shí)現(xiàn) strStr(),我們先來看題面:
https://leetcode-cn.com/problems/implement-strstr/
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
題意
樣例
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
題解
class?Solution?{
????public?int?strStr(String haystack, String needle)?{
?????????return?haystack.indexOf(needle);
????}
}

class?Solution?{
????public?int?strStr(String haystack, String needle) {
????????if(needle.equals("")||haystack.equals(needle)){
????????????return?0;
????????}
????????int?index=-1;
????????if(haystack.contains(needle)){
????????????String[] str=haystack.split(needle);
????????????if(str.length>=1){
????????????????index=str[0].length();
????????????}else?{
????????????????index=0;
????????????}
????????}else{
????????????????index=-1;
????????????}
????????return?index;
????}
}
上期推文:
