일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- sql코테
- GenAI
- 릿코드
- two-pointer
- 니트코드
- SQL
- stratascratch
- slidingwindow
- Python3
- 리트코드
- dfs
- 슬라이딩윈도우
- 투포인터
- Python
- heap
- nlp
- 코드업
- 자연어처리
- 파이썬
- 알고리즘
- gcp
- tree
- codeup
- Stack
- 생성형AI
- medium
- GenerativeAI
- LeetCode
- 파이썬기초100제
- 파이썬알고리즘
Archives
- Today
- Total
Tech for good
[Leetcode/Greedy] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence 본문
IT/Computer Science
[Leetcode/Greedy] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Diana Kang 2025. 2. 17. 23:40class 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] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence (0) | 2025.02.18 |
---|---|
[Leetcode/TwoPointer] 189. Rotate Array (0) | 2025.02.18 |
[Leetcode/Backtracking] 465. Optimal Account Balancing (0) | 2025.02.17 |
[Leetcode/Binary Search] 4. Median of Two Sorted Arrays (0) | 2025.02.17 |
[Leetcode/Hash Map+Sorting] 3167. Better Compression of String (0) | 2025.02.17 |