Check If a Word Occurs As a Prefix of Any Word in a Sentence LeetCode Solution - The Coding Shala
Home >> LeetCode >> check if a word occurs as a prefix of any word in a sentence
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Check If a Word Occurs As a Prefix of Any Word in a Sentence problem and will implement its solution in Java.
Check If a Word Occurs As a Prefix of Any Word in a Sentence Problem
Given a sentence that consists of some words separated by a single space, and a search word. You have to check if the search word is a prefix of any word in a sentence. Return the index of the word in a sentence where the search word is a prefix of this word (1-indexed). If the search word 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.
Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is the prefix of "burger" which is the 4th word in the sentence.
Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is the prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
Input: sentence = "hello from the other side", searchWord = "they"
Output: -1
Practice this problem on LeetCode(Click Here).
Check If a Word Occurs As a Prefix of Any Word in a Sentence Java Solution
Approach 1
Simple solution by using split and Java's startsWith() method.
Java Program:
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; } }
Other Posts You May Like
- LeetCode - Number of a Good Pairs
- LeetCode - Running SUm of 1d Array
- LeetCode - Friends of Appropriate Ages
- LeetCode - Range Sum Query Immutable
- LeetCode - Consecutive Characters
Comments
Post a Comment