19.2.3 [LeetCode 38] Count and Say
阿新 • • 發佈:2019-02-03
clas n+1 編號 opened terms 題解 inpu represent !=
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 where 1 ≤ n ≤ 30, 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"
題意
題意相當腦殘,都沒寫清楚
就是n+1編號的字符串是以count-and-say形式復述編號n的字符串的結果
題解
1 class Solution {View Code2 public: 3 string countAndSay(int n) { 4 string ans = "1"; 5 n--; 6 while (n--) { 7 string tmp = ""; 8 int p = 0, l = ans.length(); 9 for (int i = 1; i < l; i++) { 10 if (ans[i - 1] != ans[i]) { 11 charch = i - p + ‘0‘; 12 tmp += ch; 13 ch = ans[i - 1]; 14 tmp += ch; 15 p = i; 16 } 17 } 18 char ch = l - p + ‘0‘; 19 tmp += ch; 20 ch = ans[l - 1]; 21 tmp += ch; 22 ans = tmp; 23 } 24 return ans; 25 } 26 };
19.2.3 [LeetCode 38] Count and Say