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

@problem@discussion
#String#String Matching



1/**
2 * [1455] Check If a Word Occurs As a Prefix of Any Word in a Sentence
3 *
4 * 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.
5 * 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.
6 * A prefix of a string s is any leading contiguous substring of s.
7 *  
8 * Example 1:
9 *
10 * Input: sentence = "i love eating burger", searchWord = "burg"
11 * Output: 4
12 * Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
13 *
14 * Example 2:
15 *
16 * Input: sentence = "this problem is an easy problem", searchWord = "pro"
17 * Output: 2
18 * Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
19 *
20 * Example 3:
21 *
22 * Input: sentence = "i am tired", searchWord = "you"
23 * Output: -1
24 * Explanation: "you" is not a prefix of any word in the sentence.
25 *
26 *  
27 * Constraints:
28 *
29 * 1 <= sentence.length <= 100
30 * 1 <= searchWord.length <= 10
31 * sentence consists of lowercase English letters and spaces.
32 * searchWord consists of lowercase English letters.
33 *
34 */
35pub struct Solution {}
36
37// problem: https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
38// discuss: https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/discuss/?currentPage=1&orderBy=most_votes&query=
39
40// submission codes start here
41
42impl Solution {
43    pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 {
44        let mut result = 0;
45        for s in sentence.split(' ') {
46            result += 1;
47            if s.len() >= search_word.len() && s[0..search_word.len()] == search_word {
48                return result;
49            }
50        }
51        -1
52    }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_1455() {
63        assert_eq!(
64            Solution::is_prefix_of_word(
65                "this problem is an easy problem".to_string(),
66                "pro".to_string()
67            ),
68            2
69        );
70        assert_eq!(
71            Solution::is_prefix_of_word(
72                "i am tired".to_string(),
73                "ds".to_string()
74            ),
75            -1
76        );
77    }
78}
79


Back
© 2025 bowen.ge All Rights Reserved.