Check If a Word Occurs As a Prefix of Any Word in a Sentence

easy string prefix

Problem

You are given a sentence made of space-separated lowercase words and a target searchWord. Scan the words from left to right and return the 1-based index of the first word that begins with searchWord (that is, searchWord is a prefix of that word). If no word starts with searchWord, return −1.

Inputsentence = "i love eating burger", searchWord = "burg"
Output4
The words are ["i", "love", "eating", "burger"]. The 4th word "burger" starts with "burg", and it is the first one that does, so the answer is 4.

def is_prefix_of_word(sentence, search_word):
    words = sentence.split()
    for i, word in enumerate(words):
        if word.startswith(search_word):
            return i + 1
    return -1
function isPrefixOfWord(sentence, searchWord) {
  const words = sentence.split(" ");
  for (let i = 0; i < words.length; i++) {
    if (words[i].startsWith(searchWord)) return i + 1;
  }
  return -1;
}
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;
    }
}
int isPrefixOfWord(string sentence, string searchWord) {
    istringstream ss(sentence);
    string word;
    int i = 1;
    while (ss >> word) {
        if (word.rfind(searchWord, 0) == 0) return i;
        i++;
    }
    return -1;
}
Time: O(n) Space: O(n)