1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
UnknownView on LeetCode
Time: O(n·m)
Space: O(n)
Problem Overview
Find first word in sentence where the prefix is a prefix of that word.
Intuition
Find first word in sentence where the prefix is a prefix of that word. Simple string split and check.
Algorithm
- 1Split sentence into words.
- 2For each word: check if it starts with the given prefix.
- 3Return 1-indexed position of first match, or -1.
Common Pitfalls
- •1-indexed output. Check StartsWith or substring[0..prefix.length-1] == prefix.
1455.cs
C#
// Approach: Split sentence into words; return 1-indexed position of first word that starts with searchWord.
// Time: O(n·m) Space: O(n)
public class Solution
{
public int IsPrefixOfWord(string sentence, string searchWord)
{
string[] words = sentence.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].StartsWith(searchWord))
return i + 1;
}
return -1;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)