標籤:
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.
解題思路:
題目的理解很關鍵,n=1時返回“1”,n=2時返回“11”,n=3時返回"21",n=4時返回"1211"
所以肯定是用遞迴也進行求解,JAVA實現如下:
static public String countAndSay(int n) {if(n==1)return "1";return countAndSay(countAndSay(n-1));}static String countAndSay(String s){StringBuilder sb = new StringBuilder();int count = 0;char temp=‘*‘;for(int i=0;i<s.length();i++){if(temp!=s.charAt(i)){if(temp!=‘*‘){sb.append(count);sb.append(temp);}count=1;temp=s.charAt(i);}elsecount++;}sb.append(count);sb.append(temp);return sb.toString();}
Java for LeetCode 038 Count and Say