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;
    }
};
相关推荐
辰烨chenye4 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
带多刺的玫瑰14 小时前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
wabs66617 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
不会就选b17 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木18 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
Tisfy18 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历
木井巳19 小时前
【BFS/DFS 解决 FloodFill 算法】衣橱整理
java·算法·leetcode·深度优先·广度优先·宽度优先
shehuiyuelaiyuehao20 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode