📌  相关文章
📜  国际空间研究组织 | ISRO CS 2020 |问题 40(1)

📅  最后修改于: 2023-12-03 15:07:35.226000             🧑  作者: Mango

ISRO CS 2020 - Question 40

This is a question from the ISRO Computer Science 2020 exam. It tests your understanding of Python and string operations.

Problem Statement

Given a string s and an integer k, your task is to split the string into substrings of length k and find the number of unique substrings that can be formed.

Example
s = "abcabc"
k = 3

The string s can be split into the following substrings of length k:

"abc", "bca", "cab", "abc"

Note that the first and last substrings are the same.

The total number of unique substrings is 3: "abc", "bca", and "cab".

Solution

We can use a set to store the unique substrings. We can then iterate over the string s, extracting substrings of length k.

def count_substrings(s: str, k: int) -> int:
    unique_substrings = set()
    for i in range(len(s) - k + 1):
        substring = s[i:i+k]
        unique_substrings.add(substring)
    return len(unique_substrings)

The range(len(s) - k + 1) expression generates all the valid starting positions for a substring of length k. We then extract the substring using the slice notation s[i:i+k] and add it to the set of unique substrings.

Finally, we return the length of the set, which gives us the count of the unique substrings.

Conclusion

This problem tested your understanding of Python string operations, and the use of sets to store unique elements. By understanding the problem statement and working through the solution step by step, we were able to arrive at a correct answer.