leetcode 1961. Check If String Is a Prefix of Array(python)

這是我參與8月更文挑戰的第12天,活動詳情查看:8月更文挑戰markdown

描述

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

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.less

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

Example 1:post

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

Example 2:spa

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

Note:code

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 要小於 words 的長度。orm

其實思路已經出來了:leetcode

  • 初始化一個須要不斷拼接的字符串 prefix
  • 遍歷 words 中的單詞,將當前的單詞 word 拼接到 prefix 後面,判斷此時的 prefix 若是和 s 相等,直接返回 True ,不然重複此過程
  • 遍歷結束若是沒有返回 True ,則表示沒有找到 prefix ,直接返回 False

解答

class Solution(object):
    def isPrefixString(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: bool
        """
        prefix = ''
        for word in words:
            prefix += word
            if s==prefix:
                return True
        return False
        	      
		
複製代碼

運行結果

Runtime: 20 ms, faster than 93.69% of Python online submissions for Check If String Is a Prefix of Array.
Memory Usage: 13.4 MB, less than 71.17% of Python online submissions for Check If String Is a Prefix of Array.
複製代碼

解析

另外,咱們能夠直接將 words 中的單詞拼接成一個字符串 r ,而後判斷 s 是不是 r 的前綴。可是要保證不能是「僞前綴」,如 s=a ,words=["aa","aaaa","banana"] ,這種輸入應該是 False ,因此還要保證 s 的長度必須是合理的。原理同樣,換湯不換藥。字符串

解答

class Solution(object):
    def isPrefixString(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: bool
        """
        lengths = [len(words[0])]
        for word in words[1:]:
            lengths.append(len(word)+lengths[-1])
        return len(s) in lengths and ''.join(words).startswith(s)           	      
		
複製代碼

運行結果

Runtime: 20 ms, faster than 93.69% of Python online submissions for Check If String Is a Prefix of Array.
Memory Usage: 13.6 MB, less than 22.97% of Python online submissions for Check If String Is a Prefix of Array.
複製代碼

原題連接:leetcode.com/problems/ch…

您的支持是我最大的動力

相關文章
相關標籤/搜索