最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實(shí)現(xiàn)LeetCode(28.實(shí)現(xiàn)strStr()函數(shù))

 更新時(shí)間:2021年07月14日 09:35:36   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(28.實(shí)現(xiàn)strStr()函數(shù)),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 28. 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,如果子字符串長(zhǎng)度大于母字符串長(zhǎng)度,則返回 -1。然后開始遍歷母字符串,這里并不需要遍歷整個(gè)母字符串,而是遍歷到剩下的長(zhǎng)度和子字符串相等的位置即可,這樣可以提高運(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;
    }
};

我們也可以寫的更加簡(jiǎn)潔一些,開頭直接套兩個(gè) for 循環(huán),不寫終止條件,然后判斷假如j到達(dá) needle 的末尾了,此時(shí)返回i;若此時(shí) i+j 到達(dá) haystack 的長(zhǎng)度了,返回 -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;
    }
};

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(28.實(shí)現(xiàn)strStr()函數(shù))的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)實(shí)現(xiàn)strStr()函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

西藏| 芷江| 辽阳市| 班戈县| 商都县| 休宁县| 稷山县| 永善县| 乐昌市| 海阳市| 白银市| 琼海市| 涿州市| 友谊县| 昭平县| 兴仁县| 伽师县| 永顺县| 陈巴尔虎旗| 蓝田县| 文水县| 芦溪县| 治县。| 隆化县| 佛教| 鄂托克前旗| 前郭尔| 嵩明县| 陆河县| 来宾市| 宁波市| 岫岩| 抚宁县| 武鸣县| 新巴尔虎左旗| 咸阳市| 牡丹江市| 抚松县| 黄平县| 新平| 浙江省|