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;
    }
};
相关推荐
文丑颜不良啊7 小时前
LeetCode51~75题目解析
leetcode
学电子她就能回来吗8 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
文丑颜不良啊12 小时前
LeetCode1~50题目解析
leetcode
Pniubi13 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
Nil2082 天前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2082 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571972 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂2 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7702 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode