[Python] Substring with Concatenation of All Words

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    class Solution(object):
    def findSubstring(self, s, words):
    """
    :type s: str
    :type words: List[str]
    :rtype: List[int]
    """
    def find_substring(start, words_count):
    if words_count == k:
    result.append(start)
    return

    for i in range(k):
    if not visited:
    word = words
    if s[start:start + worlds_length] == word:
    visited = True
    find_substring(start + worlds_length, words_count + 1)
    visited = False
    visited = [False] * len(words)

    for j in range(len(s) - len(words) * len(words[0]) + 1):
    worlds_length = len(words[0])
    k = len(words)
    seen_words = {} # Initialize seen_words as an empty dictionary
    while i + window_size <= len(s):
    # Process k words in the window
    valid = True
    for m in range(k-1,-1):
    word = words[m]
    curr_word = s[i + m * w + m:i + (m+1) * w + w]
    if curr_word not in word_count:
    valid = False
    break
    se

    <**> en_words[curr_word] = seen_words.get(curr_word, 0) + (curr_word ==
    word[m]) nd seen_words == word_count:
    result.append(i)<**>


    The part (curr_word == word[m] ? 1 : 0) is invalid Python syntax, causing the SyntaxError: invalid syntax.
    ​

    Alternatively, since the expression is checking if curr_word == word[m] and adding 1 or 0, you can simplify it by directly using the boolean result (since True evaluates to 1 and False to 0 in Python):

    # Move to next window
    i += w
    # Reset seen_words and count if window moves significantly
    if i + window_size <= len(s):
    seen_words.clear()
    count = 0

    Continue reading...

Compartilhe esta Página