Check If a Word Occurs As a Prefix of Any Word in a Sentence
Q - 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
.
LeetCode Problem: Link | Click Here
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
// Split the sentence into separate words
String[] sentenceArray = sentence.split(" ");
int sentenceLen = sentenceArray.length;
int index = 0;
// Go through each word in the sentence
for (int i = 0; i < sentenceLen; i++) {
// Check if the current word begins with the searchWord
if (sentenceArray[i].startsWith(searchWord)) {
// If it does, note down its position (adding 1 to match human counting)
index = i + 1;
break; // Stop looking, we found a match
}
}
// If no match was found, return -1
if (index == 0) {
return -1;
} else {
// Otherwise, return the position of the word that starts with the searchWord
return index;
}
}
}
Subscribe to my newsletter
Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Gulshan Kumar
Gulshan Kumar
As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.