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: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
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
本題思路很簡單,就是讓咱們實現java的indexof方法,咱們根據循環判斷haystack中是否有needle字符就好了,固然,能夠直接調用java的api。面試
第一種解題方法,按照思路編輯,代碼以下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)bash
空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);ui
第二種解題方法,直接調用api,簡單粗暴(固然這個是不符合要求的),代碼以下this
if (haystack == null ) {
return 0;
}
return haystack.indexOf(needle);
複製代碼
時間複雜度: 該方案T(n)=O(1)spa
空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);翻譯
本題的大體解法如上所訴,本題只想到了一種方法,第二種方法是不符合要求的,偷懶專用,畢竟都選用了的語言,語言自帶的不用白不用code