給你兩個字符串 haystack 和 needle ,請你在 haystack 字符串中找出 needle 字符串的第一個匹配項的下標(下標從 0 開始)。如果 needle 不是 haystack 的一部分,則返回 -1 。
示例 1:
輸入:haystack = “sadbutsad”, needle = “sad”
輸出:0
解釋:“sad” 在下標 0 和 6 處匹配。
第一個匹配項的下標是 0 ,所以返回 0 。
示例 2:
輸入:haystack = “leetcode”, needle = “leeto”
輸出:-1
解釋:“leeto” 沒有在 “leetcode” 中出現,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 僅由小寫英文字符組成
思路
函數的實現非常簡單,只有一行代碼:return haystack.find(needle);
。這行代碼調用了string
類的find
成員函數,該函數在字符串中查找給定的子字符串,如果找到,就返回子字符串首次出現的位置;如果找不到,就返回string::npos
,這是一個特殊的值,表示未找到。在C++中,string::npos
的值等于-1,這正好滿足題目的要求。
AC代碼
/** @lc app=leetcode.cn id=28 lang=cpp** [28] 找出字符串中第一個匹配項的下標*/// @lc code=start
class Solution {
public:int strStr(string haystack, string needle) {return haystack.find(needle);}
};
// @lc code=end