Leetcode competition question practice backtracking method (1)------------generate every character string is an odd number

If you have like-minded friends, you can exchange supervision and study together. Hahaha! ! !

 

5352. Generate a string with an odd number of characters

Give you an integer  n, please return a character string, where each character appears exactly an odd number of times in the string  . n  

The returned string must contain only lowercase English letters. If there are multiple character strings that meet the requirements of the question, just return any one of them.

 

Example 1:

输入:n = 4
输出:"pppz"
解释:"pppz" 是一个满足题目要求的字符串,因为 'p' 出现 3 次,且 'z' 出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ohhh" 和 "love"。

Example 2:

输入:n = 2
输出:"xy"
解释:"xy" 是一个满足题目要求的字符串,因为 'x' 和 'y' 各出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ag" 和 "ur"。

Example 3:

输入:n = 7
输出:"holasss"

 

prompt:

  • 1 <= n <= 500

我的解答:

class Solution:
    def generateTheString(self, n: int) -> str:
        start, end, cur_len, s = 'a', 'z', 0, ''
        states = [0 for _ in range(26)]
        i, bFind = 0, False
        while i <= 26 and i >= 0:
            if bFind:
                break

            if i == 26:
                i -= 1
                continue

            while True:
                if states[i] == 0:
                    j = 1
                else:
                    j = states[i] + 2

                cur_len-=states[i]
                if cur_len + j == n:
                    states[i] = j
                    bFind = True
                    break
                elif cur_len + j > n:
                    states[i] = 0
                    i -=1
                    break
                else:
                    states[i] = j
                    cur_len += j
                    i+=1
                    break

        s = ""
        cnt = 0
        for i, j in enumerate(states):
            if j > 0:
                c = chr(ord('a')+i)*j
                s += c
                cnt+=j
        return s

 

Published 230 original articles · 160 praises · 820,000 views

Guess you like

Origin blog.csdn.net/happyAnger6/article/details/104730186