新聞中心
這篇文章主要介紹“C++下如何實(shí)現(xiàn)strStr()函數(shù)”,在日常操作中,相信很多人在C++下如何實(shí)現(xiàn)strStr()函數(shù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”C++下如何實(shí)現(xiàn)strStr()函數(shù)”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了營山免費(fèi)建站歡迎大家使用!
實(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; } };
到此,關(guān)于“C++下如何實(shí)現(xiàn)strStr()函數(shù)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
網(wǎng)頁題目:C++下如何實(shí)現(xiàn)strStr()函數(shù)
分享網(wǎng)址:http://fisionsoft.com.cn/article/ipcspc.html