溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++怎么實(shí)現(xiàn)strStr()函數(shù)

發(fā)布時(shí)間:2022-03-28 10:44:00 來源:億速云 閱讀:158 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細(xì)介紹“C++怎么實(shí)現(xiàn)strStr()函數(shù)”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C++怎么實(shí)現(xiàn)strStr()函數(shù)”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

Implement strStr() 實(shí)現(xiàn)strStr()函數(shù)

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

這道題讓我們?cè)谝粋€(gè)字符串中找另一個(gè)字符串第一次出現(xiàn)的位置,那首先要做一些判斷,如果子字符串為空,則返回0,如果子字符串長度大于母字符串長度,則返回 -1。然后開始遍歷母字符串,這里并不需要遍歷整個(gè)母字符串,而是遍歷到剩下的長度和子字符串相等的位置即可,這樣可以提高運(yùn)算效率。然后對(duì)于每一個(gè)字符,都遍歷一遍子字符串,一個(gè)一個(gè)字符的對(duì)應(yīng)比較,如果對(duì)應(yīng)位置有不等的,則跳出循環(huán),如果一直都沒有跳出循環(huán),則說明子字符串出現(xiàn)了,則返回起始位置即可,代碼如下:

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;
    }
};

我們也可以寫的更加簡潔一些,開頭直接套兩個(gè) for 循環(huán),不寫終止條件,然后判斷假如j到達(dá) needle 的末尾了,此時(shí)返回i;若此時(shí) i+j 到達(dá) haystack 的長度了,返回 -1;否則若當(dāng)前對(duì)應(yīng)的字符不匹配,直接跳出當(dāng)前循環(huán),參見代碼如下:

解法二:

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;
    }
};

讀到這里,這篇“C++怎么實(shí)現(xiàn)strStr()函數(shù)”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI