038-Count and Say

    xiaoxiao2022-07-12  153

    038-Count and Say

    报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被读作 "one 1" ("一个一") ,1111 被读作 "two 1s" ("两个一",2121 被读作 "one 2", "one 1""一个二" , "一个一") ,1211。 给定一个正整数 n ,输出报数序列的第 n 项。 注意:整数顺序将表示为一个字符串。 class Solution: def countAndSay(self, n: int) -> str: ans='1' while n>1: ans=self.countStr(ans) n-=1 return ans def countStr(self,s): count=0 ans="" temp=s[0] for i in range(len(s)): if s[i]==temp: count+=1 else: ans+=str(count)+temp temp=s[i] count=1 ans+=str(count)+temp return ans
    最新回复(0)