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

1. 题目

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

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

如果 s 是 words 的 前缀字符串 ,返回 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;
    }
};
相关推荐
longlongzihan32 分钟前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
smj2302_796826526 小时前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
青山木7 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
垆边人似月.7 小时前
字符串重排后最大字典序
算法·leetcode·职场和发展
代码什么用8 小时前
LeetCode-42. 接雨水
算法·leetcode
yi0119 小时前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
Navigator_Z12 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.13 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
longlongzihan13 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
kukubuzai14 小时前
二分查找系列一
数据结构·算法·leetcode