题:检查单词是否为句中其他单词的前缀
分析 :
用java的字符串来处理还是比较容易的,先用
split
方法将文章按空格拆开,得到单词数组。由于题目询问的是文章中的单词是否包含指定字符串的前缀。
因此对于每个单词:
- 先判断它的长度够不够包含指定字符串。
- 如果足够长,则取前面一段与指定字符串做比较,相等了就是包含这个指定字符串,返回这个单词的下标+1即可。
- 最后不要忘记在整个循环结束后加上无答案的结果的
-1
.
package com.leetcode;
public class Solution1 {
// 检查单词是否为句中其他单词的前缀
public int isPrefixOfWord(String sentence,String searchWord) {
if(0 == sentence.length())
{
return -1;
}
String[] words = sentence.split(" ");
for(int i = 0; i < words.length;i++) {
if(words[i].length() >= searchWord.length()) {
if(words[i].substring(0,searchWord.length()).equals(searchWord)) {
return i+1;
}
}
}
return -1;
}
public static void main(String[] args) {
String sentence1 = "Li Meng Zhu is the most beautiful girl";
String search1 = "gi";
Solution1 solution = new Solution1();
int result = solution.isPrefixOfWord(sentence1, search1);
System.out.println("匹配结果:"+result); // 8
}
}