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
- 1408. String Matching in an Array(Unknown)
- 58. Length of Last Word(Easy)
- 179. Largest Number(Medium)
- 212. Word Search II(Hard)
- 214. Shortest Palindrome(Hard)
- 474. Ones and Zeroes(Medium)