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;
    }
};
相关推荐
f3iiish6 小时前
3783. 整数的镜像距离 力扣
算法·leetcode
小雅痞7 小时前
[Java][Leetcode hard] 135. 分发糖果
java·算法·leetcode
嘻嘻哈哈樱桃7 小时前
数据流中的中位数 力扣--160
算法·leetcode·职场和发展
j_xxx404_8 小时前
力扣算法题:字符串(最长公共前缀|最长回文子串)
c++·算法·leetcode
人道领域8 小时前
【LeetCode刷题日记】:344,541-字符串反转字符串反转技巧:双指针原地交换法
算法·leetcode·面试
木子墨51617 小时前
LeetCode 热题 100 精讲 | 并查集篇:最长连续序列 · 岛屿数量 · 省份数量 · 冗余连接 · 等式方程的可满足性
数据结构·c++·算法·leetcode
故事和你9121 小时前
洛谷-算法1-7-搜索3
数据结构·c++·算法·leetcode·动态规划
y = xⁿ1 天前
20天速通LeetCode day07:前缀和
数据结构·算法·leetcode
小雅痞1 天前
[Java][Leetcode hard] 42. 接雨水
java·开发语言·leetcode
北顾笙9801 天前
day26-数据结构力扣
数据结构·算法·leetcode