1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public int isPrefixOfWord(String sentence, String searchWord) { int wordIndex = 1; for (int i = 0; i < sentence.length(); ) { int j = i; while (j < sentence.length() && sentence.charAt(j) != ' ') { j++; }
if (isPrefix(sentence, i, j, searchWord)) { return wordIndex; } wordIndex++; i = j + 1; }
return -1; }
private boolean isPrefix(String sentence, int startIndex, int endIndex, String searchWord) { for (int i = 0; i < searchWord.length(); i++) { if (startIndex + i >= endIndex || sentence.charAt(startIndex + i) != searchWord.charAt(i)) { return false; } }
return true; } }
|
References
1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence