LeetCode 1455: Check If a Word Occurs As a Prefix of Any Word in a Sentence Solution
Master LeetCode problem 1455 (Check If a Word Occurs As a Prefix of Any Word in a Sentence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Problem Explanation
Explanation
To solve this problem, we will split the sentence into words and check if the searchWord is a prefix of any word in the sentence. We can achieve this by iterating through each word in the sentence, checking if the word starts with the searchWord. If a match is found, we return the index of that word.
- Split the sentence into words.
- Iterate through each word and check if it starts with the searchWord.
- Return the index of the word if a match is found, else return -1.
Time Complexity: O(n), where n is the number of words in the sentence. Space Complexity: O(1) since we are not using any extra space.
Solution Code
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; // 1-indexed
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1455 (Check If a Word Occurs As a Prefix of Any Word in a Sentence)?
This page provides optimized solutions for LeetCode problem 1455 (Check If a Word Occurs As a Prefix of Any Word in a Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1455 (Check If a Word Occurs As a Prefix of Any Word in a Sentence)?
The time complexity for LeetCode 1455 (Check If a Word Occurs As a Prefix of Any Word in a Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1455 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1455 in Java, C++, or Python.