【leetcode】報數(Python解答)
阿新 • • 發佈:2018-12-17
題目:
報數序列是一個整數序列,按照其中的整數的順序進行報數,得到下一個數。其前五項如下:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1
被讀作 "one 1"
("一個一"
) , 即 11
。11
被讀作 "two 1s"
("兩個一"
), 即 21
。21
被讀作 "one 2"
, "one 1"
("一個二"
, "一個一"
) , 即 1211
。
給定一個正整數 n(1 ≤ n ≤ 30),輸出報數序列的第 n 項。
注意:整數順序將表示為一個字串。
示例 1:
輸入: 1 輸出: "1"
示例 2:
輸入: 4 輸出: "1211"
Python解答:
程式碼:
class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ answer=['開始','1','11','21','1211','111221'] for i in range(5,31): lenth=len(answer[i]) target=answer[i]+'*'#改造字串,防止target[i+1]無法被查詢 j=0 num=1 Temp='' while j<lenth: if target[j]==target[j+1]: num=num+1#計數:記錄連續相同數字的個數 j=j+1 continue#跳到下一次迴圈 else: value=target[j]#記錄當前檢驗的數字的值 Temp=Temp+str(num)+str(value)#生成組成字串的一部分 num=1#把計數器置為1 j=j+1 continue answer.append(Temp) return answer[n]
博主的效率邏輯清晰,程式碼移動,但效率很低:
還有很大的提升空間,下面是排行榜上兩種效率較高的解答:
解答1:
class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ if n == 1: return '1' sour = '1' for i in range(n - 1): res = '' st = sour[0] cnt = 0 for ss in sour + '.': if ss == st: cnt += 1 else: res = res + str(cnt) + st st = ss cnt = 1 sour = res return sour
解答2:
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for _ in range(n - 1):
cur = res[0]
count = 0
temp = ''
for i in res:
if i == cur:
count += 1
else:
temp += str(count) + cur
cur = i
count = 1
temp += str(count) + cur
res = temp
return res
C語言解答:
演算法思路相同,需要主要的兩點:
1.C語言中的字串的拼接:
【標頭檔案】#include <string.h>
【原型】:char
*
strcat
(
char
*dest,
const
char
*src);
【引數】: dest 為目標字串指標,src 為源字串指標。
參考:傳送門
2.動態陣列的申請:
在stdlib.h中的malloc函式可用於動態記憶體分配,他的引數是需要分配的記憶體位元組(字元)數
void *malloc(size);
在本題中的應用就是:
1 char* res =(char*)malloc((digitsSize+1)*sizeof(char));
程式碼:略