LC 1961.Check If String Is a Prefix of Array

题目描述

这是 LeetCode 上的 1961. 检查字符串是否为数组前缀 - 力扣(LeetCode) ,难度为简单

给你一个字符串 s 和一个字符串数组 words ,请你判断 s 是否为 words前缀字符串

字符串 s 要成为 words前缀字符串 ,需要满足:s 可以由 words 中的前 kk正数 )个字符串按顺序相连得到,且 k 不超过 words.length

如果 swords前缀字符串 ,返回 true ;否则,返回 false

示例 1:

1
2
3
4
输入:s = "iloveleetcode", words = ["i","love","leetcode","apples"]
输出:true
解释:
s 可以由 "i""love""leetcode" 相连得到。

示例 2:

1
2
3
4
输入:s = "iloveleetcode", words = ["apples","i","love","leetcode"]
输出:false
解释:
数组的前缀相连无法得到 s 。

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • 1 <= s.length <= 1000
  • words[i]s 仅由小写英文字母组成

解答

方法一:模拟

根据题目要求进行模拟即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean isPrefixString(String s, String[] words) {
int i = 0;
for (String w : words) {
int j = 0;
while (j < w.length()) {
if (i >= s.length()) {
break;
} else if (w.charAt(j) != s.charAt(i)) {
return false;
}
++i;
++j;
}
if (i == s.length()) {
return j == w.length(); // 注意题目的要求
}
}
return false;
}
}
  • 时间复杂度\(O(min(n, m))\),其中 ns 的长度, mwords 中所有字符串的长度之和。

  • 空间复杂度\(O(1)\)

每题一图


LC 1961.Check If String Is a Prefix of Array
https://chen-huaneng.github.io/2024/01/24/2024-1-24-2024-01-24-lc-1961/
作者
Abel
发布于
2024年1月24日
更新于
2024年1月24日
许可协议