LeetCode | Count and Say(統計並輸出)
阿新 • • 發佈:2019-02-14
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 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 sequence.
Note: The sequence of integers will be represented as a string.
其實題目很簡單,就是計算個數,並填充到新的陣列中。由於對C++不熟悉,如何給string加上一個字元還不太懂,不過參考了別人的總算寫出來了,但其中機理還是不明白。string型別,除了可以直接加字串或者string變數外,還能加上一個字元!
class Solution { public: string countAndSay(int n) { string str; str = "1"; while(--n){ string temp; char pre = str[0]; int count = 1; for(string::size_type i = 1;i < str.size();i++){ if(str[i] == pre) count++; else{ char ch = count + '0'; temp = temp + ch + pre; pre = str[i]; count = 1; } } char ch = count + '0'; temp = temp + ch + pre; str = temp; } return str; } };