일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Azure
- 빅데이터
- Python
- 투포인터
- 릿코드
- 머신러닝
- 파이썬기초
- nlp
- GenerativeAI
- GenAI
- 구글퀵랩
- 코드업
- 자연어처리
- 파이썬기초100제
- 생성형AI
- LeetCode
- 알고리즘
- Microsoft
- 데이터사이언스
- 리트코드
- 클라우드
- gcp
- 파이썬
- TwoPointer
- C#
- 파이썬알고리즘
- 코드업파이썬
- codeup
- Blazor
- Python3
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:48class 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 |