LeetCode 38. Count and Say
原题链接在这里:https://leetcode.com/problems/count-and-say/
题目:
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.
题解:
后一个结果是在前一个基础上得出的,采用pre 和 cur替换.
当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个.
计算相同char的个数先append进去.
Time Complexity: O(n * cur.length()). Space: O(cur.length()).
AC Java:
1 class Solution { 2 public String countAndSay(int n) { 3 if(n <= 0){ 4 return ""; 5 } 6 7 StringBuilder sb = new StringBuilder("1"); 8 for(int k = 1; k<n; k++){ 9 String pre = sb.toString(); 10 sb = new StringBuilder(); 11 int count = 1; 12 for(int i = 1; i<pre.length(); i++){ 13 if(pre.charAt(i) == pre.charAt(i-1)){ 14 count++; 15 }else{ 16 sb.append(count); 17 sb.append(pre.charAt(i-1)); 18 count = 1; 19 } 20 } 21 22 sb.append(count); 23 sb.append(pre.charAt(pre.length()-1)); 24 } 25 26 return sb.toString(); 27 } 28 }