C++實(shí)現(xiàn)LeetCode(28.實(shí)現(xiàn)strStr()函數(shù))
[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().
這道題讓我們在一個字符串中找另一個字符串第一次出現(xiàn)的位置,那首先要做一些判斷,如果子字符串為空,則返回0,如果子字符串長度大于母字符串長度,則返回 -1。然后開始遍歷母字符串,這里并不需要遍歷整個母字符串,而是遍歷到剩下的長度和子字符串相等的位置即可,這樣可以提高運(yùn)算效率。然后對于每一個字符,都遍歷一遍子字符串,一個一個字符的對應(yīng)比較,如果對應(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;
}
};
我們也可以寫的更加簡潔一些,開頭直接套兩個 for 循環(huán),不寫終止條件,然后判斷假如j到達(dá) needle 的末尾了,此時返回i;若此時 i+j 到達(dá) haystack 的長度了,返回 -1;否則若當(dāng)前對應(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用C++實(shí)現(xiàn)通訊錄管理系統(tǒng)的完整代碼
通訊錄是一個可以記錄親人、好友信息的工具,下面這篇文章主要給大家介紹了關(guān)于利用C++實(shí)現(xiàn)通訊錄管理系統(tǒng)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
C語言中fchdir()函數(shù)和rewinddir()函數(shù)的使用詳解
這篇文章主要介紹了C語言中fchdir()函數(shù)和rewinddir()函數(shù)的使用詳解,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
C++ 中boost::share_ptr智能指針的使用方法
這篇文章主要介紹了C++ 中boost::share_ptr智能指針的使用方法的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-10-10
C語言程序設(shè)計第五版譚浩強(qiáng)課后答案(第二章答案)
這篇文章主要介紹了C語言程序設(shè)計第五版譚浩強(qiáng)課后答案(第二章答案),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-04-04
C語言數(shù)據(jù)結(jié)構(gòu)二叉樹簡單應(yīng)用
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)二叉樹簡單應(yīng)用的相關(guān)資料,需要的朋友可以參考下2017-05-05

