[LeetCode] 1961. Check If String Is a Prefix of Array

Given a string s and an array of strings words, determine whether s is a prefix string of words.

A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.

Return true if s is a prefix string of words, or false otherwise.

Example 1:

Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.

Example 2:

Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • 1 <= s.length <= 1000
  • words[i] and s consist of only lowercase English letters.

检查字符串是否为数组前缀。

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

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

如果 s 是 words 的 前缀字符串 ,返回 true ;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-string-is-a-prefix-of-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道字符串的题,题目其实不难但是题目的英文描述不是很好懂。题目让你判断 input 字符串 S 是否是由 input 数组 words 里面的单词前缀组成的。这里所谓前缀的意思是 words 里面单词的相对位置是不能变的,这也就是第一个例子 iloveleetcode 可以由 i + love + leetcode 组成,但是第二个例子是无法组成的原因。

了解了题意之后,那么我们的思路就是创建一个 StringBuilder,然后对数组 words 里面的单词逐个添加,当 StringBuilder 的长度 == s 的长度的时候,我们可以判断一下两者是否相等。如果相等则说明 s 是 words 的 前缀字符串,反之就不是。这里我们无需判断两者长度不等的情况,因为如果 StringBuilder 不够长,那么我们还不能判断 s 是否是 StringBuilder 的前缀。

时间O(n) - words 数组的长度

空间O(n) - StringBuilder

Java实现

 1 class Solution {
 2     public boolean isPrefixString(String s, String[] words) {
 3         int len = s.length();
 4         StringBuilder sb = new StringBuilder();
 5         for (String w : words) {
 6             sb.append(w);
 7             if (sb.length() == len) {
 8                 if (!s.startsWith(sb.toString())) {
 9                     return false;
10                 } else {
11                     return true;
12                 }
13             }
14         }
15         return false;
16     }
17 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/15142548.html