【1455】检查单词是否为句中其他单词的前缀
前面这个是我写的:
#include <iostream> // 输入输出
#include <vector> // 可变长度数组
#include <unordered_map> // hashmap
#include <stack> // 栈
#include <string> // 字符串
#include <queue> // 队列
using namespace std;
/// <summary>
/// 输出容器中的内容
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
template<typename T>
void print(T t) {
for (typename T::const_iterator it = t.begin(); it != t.end() - 1; ++it) {
cout << *it << ", ";
}
cout << *(t.end() - 1) << endl;
}
////////////////////////////////////////////////////////////////////////////////
/// 这里放 OJ 的类
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
int i = 0;
int num = 0;
while (true) {
// 找到第一个非空格的字符
while (sentence[i] == ' ' && i < sentence.length()) i++;
// 判断是否没有找到
if (i >= sentence.length() - 1) return -1;
num++;
int flag = 1;
for (int j = 0; j < searchWord.length(); j++) {
if (i + j > sentence.length()) return -1;
if (searchWord[j] != sentence[i+j]) {
while (sentence[i] != ' ' && i < sentence.length()) i++;
flag = 0;
break;
}
}
if (flag == 1) return num;
}
}
};
////////////////////////////////////////////////////////////////////////////////
int main() {
/*print<vector<int>>({ 1, 2, 3, 4 });*/
Solution s;
cout << s.isPrefixOfWord("i am tired", "you") << endl;
return 0;
}
class Solution {
public:
bool isPrefix(const string &sentence, int start, int end, const string &searchWord) {
for (int i = 0; i < searchWord.size(); i++) {
if (start + i >= end || sentence[start + i] != searchWord[i]) {
return false;
}
}
return true;
}
int isPrefixOfWord(string sentence, string searchWord) {
int n = sentence.size(), index = 1, start = 0, end = 0;
while (start < n) {
while (end < n && sentence[end] != ' ') {
end++;
}
if (isPrefix(sentence, start, end, searchWord)) {
return index;
}
index++;
end++;
start = end;
}
return -1;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solution/jian-cha-dan-ci-shi-fou-wei-ju-zhong-qi-pqpu2/
来源: 力扣 (LeetCode)
著作权归作者所有. 商业转载请联系作者获得授权, 非商业转载请注明出处.
文章评论