1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
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.
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.