1961. 检查字符串是否为数组前缀 - 力扣

1. 题目

给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words前缀字符串

字符串 s 要成为 words前缀字符串 ,需要满足:s 可以由 words 中的前 kk正数 )个字符串按顺序相连得到,且 k 不超过 words.length

如果 swords前缀字符串 ,返回 true ;否则,返回 false

2. 示例

3. 分析

法一:直接拼接数组的每个字符串比较是否与 s 相等:

cpp 复制代码
class Solution {
public:
    bool isPrefixString(string s, vector<string>& words) {       
        string str;
        for(int i = 0; i < words.size(); i++)
        {
            for(int j = 0; j < words[i].size(); j++)
            {
                str += words[i][j];
            }       
            if(str == s) return true;                     
        }
        return false;
    }
};

法二:逐个字符比较是否相等即可,若有一个不同则false:

cpp 复制代码
class Solution {
public:
    bool isPrefixString(string s, vector<string>& words) {       
        int pos = 0, n = s.size();
        for(int i = 0; i < words.size(); i++)
        {
            for(int j = 0; j < words[i].size(); j++)
            {
                if(pos < n && words[i][j] == s[pos]) pos++;
                else return false;       
            }
            if(pos == n) return true;
        }
        return false;
    }
};
相关推荐
浮灯Foden25 分钟前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
执子手 吹散苍茫茫烟波2 小时前
leetcode415. 字符串相加
java·leetcode·字符串
执子手 吹散苍茫茫烟波3 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法
山顶风景独好4 小时前
【Leetcode】随笔
数据结构·算法·leetcode
·白小白8 小时前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
墩墩同学10 小时前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
1白天的黑夜112 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
m0_6728137712 小时前
Leetcode-3427变长子数组求和
leetcode
崎岖Qiu12 小时前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归
Swift社区1 天前
Swift 实战:实现一个简化版的 Twitter(LeetCode 355)
leetcode·swift·twitter