[Leetcode38]Count and Say
阿新 • • 發佈:2018-11-27
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 = “1”,從1開始往後的字串都是指前面一個字串按順序出現的值得計數形式。
python:
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ res = "1" if n == 1: return res for i in range(1,n): j = 0 count = 1 temp = "" while j < len(res): s = res[j] if j == len(res) - 1: temp += str(count) temp += s break if res[j] == res[j+1]: count += 1 j += 1 else: temp += str(count) temp += s count = 1 j += 1 res = temp return res
C++:
class Solution { public: string countAndSay(int n) { string res = "1"; if(n == 1) return res; for(int i = 1;i < n;i++){ int j = 0; int count = 1; string temp; while(j < res.length()){ char s(res[j]); if(j == res.length() - 1){ temp += to_string(count); temp += s; break; } if(res[j+1] == res[j]){ count += 1; j += 1; } else{ temp += to_string(count); temp += s; count = 1; j += 1; } } res = temp; } return res; } };