Description:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Note:
無
Solution:
Analysis and Thinking:
題目要求實現strStr()函數的功能,找一個字符串中是否包含另一個字符串,並返回包含的位置,使用暴力求解即可
Steps:
1. 定義兩個變量分別存儲haystack以及needle的傳長度
2. 遍歷haystack,設置一記錄器counter,每次從當前位置開始查到當前值加needle長度長的子串
3. 判斷當前遍歷的子串是否與needle相等,如果是,返回當前位置值
4. 遍歷無果,返回-1
Codes:
class Solution {
public:
int strStr(string haystack, string needle) {
int i = -1;
int lengthNeed = needle.size();
int lengthHay = haystack.size();
while(++i <= lengthHay-lengthNeed)
{
string record = haystack.substr(i, lengthNeed);
if(record == needle) return i;
}
return -1;
}
};
Results: