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;
    }
};
相关推荐
青山木17 小时前
Hot 100 --- 组合总和
java·数据结构·算法·leetcode
zander25817 小时前
LeetCode 46. 全排列
算法·leetcode·深度优先
会编程的土豆19 小时前
LeetCode 热题 HOT100(一):哈希表与双指针入门(Go 实现)
算法·leetcode·职场和发展
Tisfy20 小时前
LeetCode 3518.最小回文排列 II:试填法(组合数学)
算法·leetcode·题解·组合数学·计数·回文串·试填法
小poop1 天前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
玖玥拾2 天前
LeetCode 27 移除元素
算法·leetcode
hanlin032 天前
刷题笔记:力扣第704、977、209题(数组相关)
笔记·算法·leetcode
Rabitebla2 天前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode
玖玥拾2 天前
LeetCode 58 最后一个单词的长度
算法·leetcode
hanlin032 天前
刷题笔记:力扣第19题-删除链表的倒数第N个结点
笔记·leetcode·链表