4/31 每日一題
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 104haystackandneedleconsist of only lowercase English characters.
import re
haystack = "sadbutsad"
needle = "sad"
if re.search(needle,haystack):
for i in re.finditer(needle,haystack):
#finditer是一個可迭代資料,可以找出「每次」匹配到的索引
print(i.span()) #回傳一組tuple
if re.search(needle,haystack):
print(re.search(needle,haystack).start())
#start()回傳開始的索引,但他只會找到第一個
---------------
終端機
PS C:\Users\K\OneDrive\桌面\AUTOKI> & C:/Users/K/AppData/Local/Programs/Python/Python311/python.exe c:/Users/K/OneDrive/桌面/AUTOKI/tes.py
(0, 3)
(6, 9)
0
PS C:\Users\K\OneDrive\桌面\AUTOKI>
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁