Easy
题目描述
给你一个由若干单词组成的句子 sentence ,单词间由单个空格分隔。另给你一个字符串 searchWord 。
请你检查 searchWord 是否为句子 sentence 中任意单词的前缀。
- 如果
searchWord是某一个单词的前缀,则返回句子sentence中该单词所对应的下标(下标从 1 开始)。 - 如果
searchWord是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。 - 如果
searchWord不是任何单词的前缀,则返回 -1 。
字符串 s 的 前缀 是 s 的任何前导连续子字符串。
示例 1:
输入:sentence = "i love eating burger", searchWord = "burg"
输出:4
解释:"burg" 是 "burger" 的前缀,而 "burger" 是句子中第 4 个单词。
示例 2:
输入:sentence = "this problem is an easy problem", searchWord = "pro"
输出:2
解释:"pro" 是 "problem" 的前缀,而 "problem" 是句子中第 2 个和第 6 个单词,但是我们返回最小下标 2 。
示例 3:
输入:sentence = "i am tired", searchWord = "you"
输出:-1
解释:"you" 不是句子中任何单词的前缀。
提示:
1 <= sentence.length <= 1001 <= searchWord.length <= 10sentence由小写英文字母和空格组成searchWord由小写英文字母组成
解题思路
这道题目要求检查一个字符串是否是句子中某个单词的前缀,并返回第一个匹配单词的位置(1-indexed)。
解法一:分割字符串(推荐)
- 将句子按空格分割成单词数组
- 遍历每个单词,检查
searchWord是否是该单词的前缀 - 可以使用字符串的
startsWith方法或手动比较前缀 - 返回第一个匹配的单词位置(注意是1-indexed)
解法二:双指针
- 使用双指针直接在原句子中扫描,不需要额外的空间分割字符串
- 当遇到空格时表示一个单词结束,检查当前单词是否匹配
解法三:字符串查找
- 可以使用字符串的内置方法进行模式匹配
考虑到代码简洁性和可读性,推荐使用解法一。该方法思路清晰,容易理解和实现。
代码实现
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
istringstream iss(sentence);
string word;
int index = 1;
while (iss >> word) {
if (word.length() >= searchWord.length() &&
word.substr(0, searchWord.length()) == searchWord) {
return index;
}
index++;
}
return -1;
}
};
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
words = sentence.split()
for i, word in enumerate(words):
if word.startswith(searchWord):
return i + 1
return -1
public class Solution {
public int IsPrefixOfWord(string sentence, string searchWord) {
string[] words = sentence.Split(' ');
for (int i = 0; i < words.Length; i++) {
if (words[i].StartsWith(searchWord)) {
return i + 1;
}
}
return -1;
}
}
var isPrefixOfWord = function(sentence, searchWord) {
const words = sentence.split(' ');
for (let i = 0; i < words.length; i++) {
if (words[i].startsWith(searchWord)) {
return i + 1;
}
}
return -1;
};
复杂度分析
| 复杂度类型 | 分析 |
|---|---|
| 时间复杂度 | O(n·m),其中 n 是句子长度,m 是 searchWord 长度。需要遍历所有单词并检查前缀 |
| 空间复杂度 | O(n),需要存储分割后的单词数组 |