Leetcodes Solution 28 Implement strStr()

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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

思路1

用索引i對haystack遍歷

用j來記錄needle和haystack相等的個數,如果個數等於needle的長度,則返回haystack當前的索引i。

class Solution {public: int strStr(string haystack, string needle){ int m = haystack.length(), n = needle.length(); if(!n) return 0; for(int i = 0; i < m - n + 1; i++){ int j = 0; for(; j < n; j++) if(haystack[i + j] != needle[j]) break; if(j == n) return i; } return -1; }};

推薦閱讀:

[數據結構]表達式樹——手動eval()
GitHub CEO:GitHub 十年,感謝有你
【重磅】慕課網認證作者招募 | 打造個人品牌 so easy !
Leetcodes Solutions 9 Palindrome Number
A Discipline of Programming 筆記,1-4章

TAG:演算法 | 數據結構 | 編程 |