[Leetcode] count and say 計數和說
阿新 • • 發佈:2017-06-20
str 一個 實現 當前 ger repr begin lee http
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
題意:返回第n個序列,第i+1個字符串是第i個字符串的讀法。參考:Grandyang和JustDoIT的博客。
思路:算法就是對於前一個數,找出相同元素的個數,把個數和該元素存到新的string裏。代碼需要兩個循環,第一個是為找到第n個,第二是為了,根據上一字符串的信息來實現當前的字符串。
1 class Solution { 2 public: 3 string countAndSay(int n) 4 { 5 if(n<1) return NULL; 6 7 string res="1"; 8 for(int i=1;i<n;++i) 9 { 10 string temp; //當前序列 11 res.push_back(‘*‘); 12 int count=0; //重復的個數 13 for(int j=0;j<res.size();++i) 14 { 15 if(j==0) 16 count++; 17 else 18 {19 if(res[j] !=res[j-1]) 20 { 21 temp.push_back(count+‘0‘); 22 temp.push_back(res[j-1]); 23 count=1; 24 } 25 else 26 ++count; 27 } 28 } 29 res=temp; 30 } 31 return res; 32 } 33 };
[Leetcode] count and say 計數和說