日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode集锦(十) - 第28题 Implement StrStr

發布時間:2025/6/17 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode集锦(十) - 第28题 Implement StrStr 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

LeetCode集錦(十) - 第28題 Implement StrStr

問題

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: 2Example 2:Input: haystack = "aaaaa", needle = "bba" Output: -1Clarification:What should we return when needle is an empty string? This is a great question to ask during an interview.For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().復制代碼

翻譯:

實現strStr ()。
返回haystack中needle的第一次出現的索引,如果針不是haystack的一部分,返回-1。
示例1:
輸入:haystack = "hello", needle = "ll"
輸出:2
示例2:
輸入:haystack = "aaaaa", needle = "bba"
輸出:1
澄清:
當needle是空字符串時,我們應該返回什么?這是一個非常適合在面試中問的問題。
對于這個問題,當needle為空字符串時,我們將返回0。這與C的strstr()和Java的indexOf()一致。


解題思路

本題思路很簡單,就是讓我們實現java的indexof方法,我們根據循環判斷haystack中是否有needle字符就行了,當然,可以直接調用java的api。

解題方法

  • 第一種解題方法,按照思路編輯,代碼如下

    if (haystack == null || "".equals(needle)) {return 0;}int len = haystack.length() - needle.length()+1;int needLen = needle.length();for (int i = 0; i < len; i++) {if (haystack.charAt(i) != needle.charAt(0)) {continue;}int m;for (m = 1; m < needle.length(); m++) {if (haystack.charAt(i + m) != needle.charAt(m)) {break;}}if (m == needLen) {return i;}}return -1; 復制代碼

    時間復雜度: 該方案用了循環,循環層數為2,所以O(f(n))=O(Mn),即T(n)=O(n^2)

    空間復雜度: 該方案沒有使用額外的空間,所以空間復雜度是O(1);

  • 第二種解題方法,直接調用api,簡單粗暴(當然這個是不符合要求的),代碼如下

    if (haystack == null ) {return 0;}return haystack.indexOf(needle); 復制代碼

    時間復雜度: 該方案T(n)=O(1)

    空間復雜度: 該方案沒有使用額外的空間,所以空間復雜度是O(1);

  • 總結

    本題的大致解法如上所訴,本題只想到了一種方法,第二種方法是不符合要求的,偷懶專用,畢竟都選用了的語言,語言自帶的不用白不用

    轉載于:https://juejin.im/post/5cda3521f265da03b204515b

    總結

    以上是生活随笔為你收集整理的LeetCode集锦(十) - 第28题 Implement StrStr的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。