题目来源:
leetcode题目,网址:1455. 检查单词是否为句中其他单词的前缀 - 力扣(LeetCode)
解题思路:
将句子以单个空格分割后逐个判断即可。
解题代码:
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
int res=-1;
int length=searchWord.length();
String[] words=sentence.split(" ");
for(int i=0;i<words.length;i++){
String word=words[i];
if(word.length()>=length && word.substring(0,length).equals(searchWord)){
res=i+1;
break;
}
}
return res;
}
}
总结:
官方题解是使用双指针确定单词范围再进行判断。