[LeetCode] 28. Implement strStr() 實現strStr()函數

 

Implement strStr().html

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.java

Example 1:git

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:github

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:api

What should we return when needle is an empty string? This is a great question to ask during an interview.oracle

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().post

 

這道題讓咱們在一個字符串中找另外一個字符串第一次出現的位置,那首先要作一些判斷,若是子字符串爲空,則返回0,若是子字符串長度大於母字符串長度,則返回 -1。而後開始遍歷母字符串,這裏並不須要遍歷整個母字符串,而是遍歷到剩下的長度和子字符串相等的位置便可,這樣能夠提升運算效率。而後對於每個字符,都遍歷一遍子字符串,一個一個字符的對應比較,若是對應位置有不等的,則跳出循環,若是一直都沒有跳出循環,則說明子字符串出現了,則返回起始位置便可,代碼以下:this

 

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty()) return 0;
        int m = haystack.size(), n = needle.size();
        if (m < n) return -1;
        for (int i = 0; i <= m - n; ++i) {
            int j = 0;
            for (j = 0; j < n; ++j) {
                if (haystack[i + j] != needle[j]) break;
            }
            if (j == n) return i;
        }
        return -1;
    }
};

 

咱們也能夠寫的更加簡潔一些,開頭直接套兩個 for 循環,不寫終止條件,而後判斷假如j到達 needle 的末尾了,此時返回i;若此時 i+j 到達 haystack 的長度了,返回 -1;不然若當前對應的字符不匹配,直接跳出當前循環,參見代碼以下:url

 

解法二:spa

class Solution {
public:
    int strStr(string haystack, string needle) {
        for (int i = 0; ; ++i) {
            for (int j = 0; ; ++j) {
                if (j == needle.size()) return i;
                if (i + j == haystack.size()) return -1;
                if (needle[j] != haystack[i + j]) break;
            }
        }
        return -1;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/28

 

相似題目:

Shortest Palindrome

Repeated Substring Pattern

 

參考資料:

https://leetcode.com/problems/implement-strstr/

https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution

https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索