[LeetCode] Check If a Word Occurs As a Prefix of Any Word in a Sentence

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

Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.

Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.

A prefix of a string s is any leading contiguous substring of s.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
fun isPrefixOfWord(sentence: String, searchWord: String): Int {
val words = sentence.split(" ")
for ((index, word) in words.withIndex()) {
if (word.startsWith(searchWord)) {
return index + 1
}
}
return -1
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/02/PS/LeetCode/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.