「 每日一练,快乐水题 」1455. 检查单词是否为句中其他单词的前缀


🔴力扣原题:

1455. 检查单词是否为句中其他单词的前缀

🟠题目简述:

给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。

如果 searchWord 是某一个单词的前缀,则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)。如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord 不是任何单词的前缀,则返回 -1 。

字符串 s 的 前缀 是 s 的任何前导连续子字符串。

🟡解题思路:

  1. 模拟大法好;
  2. 根据空格分割字符串,插入vector
  3. 然后遍历vector,检测前缀;
  4. 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;
    }
};

🔵结果展示:

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谁吃薄荷糖

你获得知识,我获得财富,双赢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值