1. 程式人生 > 其它 >LeetCode刷題(11)--實現strStr()

LeetCode刷題(11)--實現strStr()

技術標籤:刷題!!!leetcode字串

題目描述

給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。

示例:
輸入: haystack = “hello”, needle = “ll”
輸出: 2

示例:
輸入: haystack = “aaaaa”, needle = “bba”
輸出: -1

解題思路

int strStr(string haystack,string needle)
{
	string s;
	int j=0;
	int n=0;
	if(needle=="")
		return 0;
	if(haystack.length()<needle.length())
		return -1;
	n=needle.length();
	for(int i=0;i<haystack.length();i++)
	{
		s=haystack.substr(i,n);
		if(s==needle)
		{
			return j;
		}
		j++;
	}
	return -1;
}
int main()
{
	string haystack = "hello";
	string needle  = "ll";
	string haystack1 = "aaaaa";
	string needle1  = "bba";
	cout<<strStr(haystack,needle)<<endl;
	cout<<strStr(haystack1,needle1)<<endl;
}

結果:
在這裡插入圖片描述
分析:
1.定義兩個字串haystack和needle。
2.如果字串needle為空,返回0。
3.如果字串haystack的長度小於字串needle長度,返回-1。
4.獲取字串needle長度,遍歷符串haystack,每次獲取字串haystack中的needle長度,判斷獲取的字串是否等於needle字串,往後移一位。
5.第一次找到返回j,找不到j+1,繼續遍歷尋找,一直找不到返回-1。

演示
輸入: haystack = “hello”, needle = “ll”
1.i=0時,獲取haystack的前兩個字元"he",判斷是否等於"ll",不等於,j+1,繼續。

2.i=1時,獲取haystack中的兩個字元"el",判斷是否等於"ll",不等於,j+1,繼續。
3.i=2時,獲取haystack中的兩個字元"ll",判斷是否等於"ll",等於,返回j=2,結束。