JS代码:js就很便捷!startsWith()
/**
* @param {string} sentence
* @param {string} searchWord
* @return {number}
*/
var isPrefixOfWord = function(sentence, searchWord) {
let arr = sentence.split(' ');
for (let i = 0; i < arr.length; ++i) {
if (arr[i].startsWith(searchWord)) {
return i + 1;
}
}
return -1;
};
Java代码:
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
String[] arr = sentence.split(" ");
for (int i = 0; i < arr.length; ++i) {
if (arr[i].startsWith(searchWord)) {
return i + 1;
}
}
return -1;
}
}