1455.检查单词是否为句中其他单词的前缀
链接:1455.检查单词是否为句中其他单词的前缀
难度:Easy
标签:双指针、字符串、字符串匹配
简介:请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。
题解 1 - cpp
- 编辑时间:2022-08-21
- 执行用时:4ms
- 内存消耗:6.1MB
- 编程语言:cpp
- 解法介绍:分割字符串。
class Solution {
public:
    int isPrefixOfWord(string sentence, string searchWord) {
        istringstream iss(sentence);
        string tmp;
        int cnt = 1;
        while (getline(iss, tmp, ' ')) {
            int i = 0, j = 0;
            bool f = true;
            for (; i < tmp.size() && j < searchWord.size(); i++, j++) {
                if (tmp[i] != searchWord[j]) {
                    f = false;
                    break;
                }
            }
            if (f && j == searchWord.size()) return cnt;
            cnt++;
        }
        return -1;
    }
};
题解 2 - typescript
- 编辑时间:2022-08-21
- 执行用时:56ms
- 内存消耗:42.2MB
- 编程语言:typescript
- 解法介绍:分割字符串。
function isPrefixOfWord(sentence: string, searchWord: string): number {
  const list = sentence.split(' ');
  for (let i = 0; i < list.length; i++) {
    if (list[i].startsWith(searchWord)) return i + 1;
  }
  return -1;
}