Leetcode 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
You are given a sentence and a search word. The objective is to check if the search word occurs as a prefix of any word in the given sentence. If the search word is a prefix of a word in the sentence, return the index (1-based) of the first such word. If the search word does not occur as a prefix of any word in the sentence, return -1.
Example:
sentence = "i love eating burger"
, searchWord = "burg"
Output: 4
sentence = "this problem is an easy problem"
, searchWord = "pro"
Output: 2
sentence = "i am tired"
, searchWord = "you"
-1
substr
or find
function.#include <iostream>
#include <sstream>
#include <string>
int isPrefixOfWord(std::string sentence, std::string searchWord) {
std::istringstream stream(sentence);
std::string word;
int index = 1;
while (stream >> word) {
if (word.find(searchWord) == 0) {
return index;
}
index++;
}
return -1;
}
int main() {
// Test cases
std::cout << isPrefixOfWord("i love eating burger", "burg") << std::endl; // Output: 4
std::cout << isPrefixOfWord("this problem is an easy problem", "pro") << std::endl; // Output: 2
std::cout << isPrefixOfWord("i am tired", "you") << std::endl; // Output: -1
return 0;
}
O(n)
n
is the number of words in the sentence.O(k)
on average for each word comparison.
k
is the length of the search word.In the worst case, the time complexity will be O(n * k)
where n
is the number of words and k
is the length of the search word.
Thus, the overall time complexity is O(n * k)
. This is efficient given the context of typical sentence and word lengths.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?