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;
    }
};
相关推荐
海琴烟Sunshine2 小时前
leetcode 383. 赎金信 python
python·算法·leetcode
cynicme8 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员8 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
Miraitowa_cheems11 小时前
LeetCode算法日记 - Day 102: 不相交的线
数据结构·算法·leetcode·深度优先·动态规划
Miraitowa_cheems11 小时前
LeetCode算法日记 - Day 101: 最长公共子序列
数据结构·算法·leetcode·深度优先·动态规划
玖剹13 小时前
二叉树递归题目(一)
c语言·c++·算法·leetcode
沧澜sincerely13 小时前
BFS & 图论【各种题型+对应LeetCode习题练习】
leetcode·图论·广度优先
不穿格子的程序员13 小时前
从零开始写算法——二分-寻找旋转排序数组中的最小值
数据结构·算法·leetcode·二分查找
小白程序员成长日记13 小时前
2025.11.13 力扣每日一题
算法·leetcode·职场和发展
_fairyland17 小时前
数据结构 力扣 练习
数据结构·考研·算法·leetcode