Skip to content

Latest commit

 

History

History
122 lines (91 loc) · 3.02 KB

File metadata and controls

122 lines (91 loc) · 3.02 KB

English Version

题目描述

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

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

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

 

示例 1:

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

示例 2:

输入: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 仅由小写英文字母组成

解法

Python3

class Solution:
    def isPrefixString(self, s: str, words: List[str]) -> bool:
        t = 0
        for i, w in enumerate(words):
            t += len(w)
            if len(s) == t:
                return ''.join(words[: i + 1]) == s
        return False

Java

class Solution {
    public boolean isPrefixString(String s, String[] words) {
        StringBuilder t = new StringBuilder();
        for (String w : words) {
            t.append(w);
            if (s.length() == t.length()) {
                return s.equals(t.toString());
            }
        }
        return false;
    }
}

C++

class Solution {
public:
    bool isPrefixString(string s, vector<string>& words) {
        string t = "";
        for (string& w : words) {
            t += w;
            if (t.size() == s.size()) return t == s;
        }
        return false;
    }
};

Go

func isPrefixString(s string, words []string) bool {
	t := ""
	for _, w := range words {
		t += w
		if t == s {
			return true
		}
	}
	return false
}

...