일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Microsoft
- 투포인터
- 코드업
- nlp
- gcp
- 슬라이딩윈도우
- heap
- 파이썬
- 구글퀵랩
- 릿코드
- dfs
- GenerativeAI
- Python3
- 파이썬기초100제
- medium
- 리트코드
- codeup
- sql코테
- 알고리즘
- stratascratch
- 파이썬알고리즘
- 자연어처리
- 생성형AI
- LeetCode
- slidingwindow
- Python
- SQL
- 니트코드
- GenAI
- two-pointer
Archives
- Today
- Total
Tech for good
[Leetcode/String Manipulation] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence 본문
IT/Computer Science
[Leetcode/String Manipulation] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Diana Kang 2025. 2. 18. 22:48

class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
words = sentence.split()
for i, word in enumerate(words):
if word.startwith(searchword):
return i+1
return -1
Explanation:
- Split the Sentence: The input sentence is split into a list of words using .split(), which automatically handles single spaces.
- Iterate Over Words: We loop through the words using enumerate(), which gives both the index (i) and the word.
- Check for Prefix: If a word starts with searchWord, we return its 1-based index (i + 1).
- Return -1 if Not Found: If no word matches the prefix condition, return -1.
Complexity Analysis:
- Time Complexity: O(n) where nn is the number of words in the sentence, since we iterate through the words once.
- Space Complexity: O(1) since we only store the words list temporarily.
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/String Manipulation] 151. Reverse Words in a String (0) | 2025.02.19 |
---|---|
[Leetcode/TwoPointer] 392. Is Subsequence (0) | 2025.02.18 |
[Leetcode/TwoPointer] 189. Rotate Array (0) | 2025.02.18 |
[Leetcode/Greedy] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence (0) | 2025.02.17 |
[Leetcode/Backtracking] 465. Optimal Account Balancing (0) | 2025.02.17 |