Skip to content

Commit 31b8ecf

Browse files
solves check if work occurs as prefix of any word in sentence
1 parent 48003bc commit 31b8ecf

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@
369369
| 1441 | [Build An Array With Stack Operation](https://leetcode.com/problems/build-an-array-with-stack-operations) | [![Java](assets/java.png)](src/BuildAnArrayWithStackOperations.java) | |
370370
| 1446 | [Consecutive Characters](https://leetcode.com/problems/consecutive-characters) | [![Java](assets/java.png)](src/ConsecutiveCharacters.java) | |
371371
| 1450 | [Number of Students Doing Homework at Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time) | [![Java](assets/java.png)](src/NumberOfStudentsDoingHomeworkAtGivenTime.java) | |
372-
| 1455 | [Check If Word Occurs as Prefix of any Word in Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | | |
372+
| 1455 | [Check If Word Occurs as Prefix of any Word in Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | [![Java](assets/java.png)](src/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence.java) | |
373373
| 1460 | [Make 2 Arrays Equal by Reversing Sub Arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) | | |
374374
| 1464 | [Maximum Product of 2 Elements in Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array) | | |
375375
| 1469 | [Find All Lonely Nodes](https://leetcode.com/problems/find-all-the-lonely-nodes) | | |
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class CheckIfAWordOccursAsAPrefixOfAnyWordInASentence {
2+
public int isPrefixOfWord(String sentence, String searchWord) {
3+
int matchIndex = -1;
4+
do {
5+
matchIndex = sentence.indexOf(searchWord, matchIndex + 1);
6+
if (matchIndex == -1) return -1;
7+
if (matchIndex == 0 || sentence.charAt(matchIndex - 1) == ' ') {
8+
return spacesUpto(sentence, matchIndex) + 1;
9+
}
10+
} while (matchIndex < sentence.length());
11+
return -1;
12+
}
13+
14+
private static int spacesUpto(String string, int endIndex) {
15+
int spaces = 0;
16+
for (int index = 0 ; index < endIndex ; index++) {
17+
if (string.charAt(index) == ' ') spaces++;
18+
}
19+
return spaces;
20+
}
21+
}

0 commit comments

Comments
 (0)