The 10th Blue Bridge Cup java-c group-different substrings

1. Problem description:

Total score for this question: 10 points
[Problem description]
A non-empty substring of a string refers to a string consisting of a continuous segment of characters with a length of at least 1 in the string. For example, the string aaab has non-empty substrings a, b, aa, ab, aaa, aab, aaab, a total of 7 substrings. Note that when calculating, only count the number of strings that are essentially different. Excuse me, how many different non-empty substrings are there in the string 0100110001010001?
[Answer Submission]
This is a question that fills in the blanks with the result. You only need to calculate the result and submit it. The result of this question is an integer. Only fill in this integer when submitting the answer, and fill in the extra content will not be scored.

2. Thinking analysis:

Analyzing the question, we can know that we need to intercept all the substrings in the string s, and then add these substrings to the set collection for deduplication, and finally return the size of the set collection. Then it is the number of different substrings. There are two ways of writing. One is to intercept the substring from the first character of the string all the way back. The outermost loop represents the substring from the current position i, and the inner loop represents the substring from the position i to the end of the string s. The second The writing method is that the interception length is len=1,2,...n, the outermost layer represents the current interception length, and the inner loop represents the interception of substrings of length len from the beginning of the string. The first method is recommended. , The first way is more natural and less detailed

3. The code is as follows:

The first:

if __name__ == '__main__':
    s = "0100110001010001"
    # 使用循环模拟, 使用set集合进行去重, 从字符串一开始开始截取
    count = set()
    for i in range(len(s)):
        for j in range(i + 1, len(s) + 1):
            count.add(s[i:j])
            # print(s[i:j])
    print(len(count))

The second type:

if __name__ == '__main__':
    s = "aaab"
    s = "0100110001010001"
    # 使用循环模拟, 使用set集合进行去重
    count = set()
    for i in range(1, len(s) + 1):
        for j in range(len(s)):
            # 截取当前位置开始长度为i的字串
            if j + i <= len(s):
                count.add(s[j:j + i])
                # print(s[j:j + i])
            else:
                break
    print(len(count))

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/114999442