🔴力扣原题:
🟠题目简述:
给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。
如果 searchWord 是某一个单词的前缀,则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)。如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord 不是任何单词的前缀,则返回 -1 。
字符串 s 的 前缀 是 s 的任何前导连续子字符串。
🟡解题思路:
- 模拟大法好;
- 根据空格分割字符串,插入
vector
; - 然后遍历
vector
,检测前缀; - over;
🟢C++代码:
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
vector<string> vecStr;
int n = sentence.length();
string str;
for(int i = 0;i < n; i++)
{
if(sentence[i] == ' ')
{
vecStr.push_back(str);
str.clear();
}
else if(i == n-1)
{
str += sentence[i];
vecStr.push_back(str);
str.clear();
}
else
{
str += sentence[i];
}
}
int nLen = vecStr.size();
int res = -1;
for(int j = 0; j < nLen; j++)
{
int npos = vecStr[j].find(searchWord);
int nStr = searchWord.length();
cout << vecStr[j] << " " << vecStr[j].substr(0, nStr) << endl;
if( npos != vecStr[j].npos && (vecStr[j].substr(0, nStr) == searchWord))
{
res = j + 1;
break;
}
}
return res;
}
};