38. Count and Say

题目

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: “1”
Example 2:

Input: 4
Output: “1211”

题意

就是针对上一个字符串使用一种规则生成下一个字符串
比如第一个字符串为“1”,其表示有1个1,则下一个字符串为“11”
对于字符串“11”而言,其表示有有2个1,则下一个字符串为“21”

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
nstr="1"
for i in range(n):
if i==0:
nstr="1"
else:
restr = ""
#for j in range(len(nstr)):
j=0
while j<len(nstr):
prec = nstr[j]
num = 1
while j + 1 < len(nstr) and nstr[j + 1] == nstr[j]:
j += 1
num += 1
#print("i=",i,"restr=",restr,"j=",j)
restr = restr + str(num) + str(nstr[j])
#print("@","i=", i, "restr=", restr, "j=", j)
j+=1
nstr = restr
print(nstr)
return nstr

后记

此处有一个python和Java的问题给搞混淆了,针对for循环的问题
如下语句:

1
2
3
for i in range(9):
i=i+2
print(i)

输出的结果是2,3,4,5,6,7,8,9,10
我的理解以及java中的结果,都是i的变化会对for循环产生影响,但是python中是没有影响的,也就是说for中修改for上的变量并不会改变for上的变量

如果觉得有帮助,给我打赏吧!