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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: td 溢出
- 下一篇: 蛋花花谈Web开发到底要不要加入人工智能