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;
    }
};
相关推荐
程序员-King.1 小时前
day140—前后指针—删除排序链表中的重复元素Ⅱ(LeetCode-82)
数据结构·算法·leetcode·链表
Remember_9931 小时前
【JavaSE】一站式掌握Java面向对象编程:从类与对象到继承、多态、抽象与接口
java·开发语言·数据结构·ide·git·leetcode·eclipse
苦藤新鸡2 小时前
16.求数组除了当前元素的所有乘积
算法·leetcode·动态规划
Tisfy2 小时前
LeetCode 1895.最大的幻方:暴力中来点前缀和优化
算法·leetcode·前缀和·矩阵·题解·暴力
Remember_9932 小时前
【数据结构】Java数据结构深度解析:栈(Stack)与队列(Queue)完全指南
java·开发语言·数据结构·算法·spring·leetcode·maven
努力学算法的蒟蒻2 小时前
day59(1.18)——leetcode面试经典150
算法·leetcode·职场和发展
程序员-King.2 小时前
day146—递归—验证二叉搜索树(LeetCode-98)
算法·leetcode·二叉树·递归
iAkuya2 小时前
(leetcode)力扣100 45二叉树的右视图(dfs,bfs)
leetcode·深度优先·宽度优先
闪电麦坤954 小时前
Leecode热题100:缺失的第一个正数(数组)
数据结构·算法·leetcode
夏鹏今天学习了吗11 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展