题目来源:https://leetcode.com/problems/count-and-say/
import java.util.ArrayList;
/**
*
* <p>
* ClassName CountAndSay
* </p>
* <p>
* Description The count-and-say sequence is the sequence of integers beginning as follows: <br/>
* 1, 11, 21, 1211, 111221, ...<br/>
*
* 1 is read off as "one 1" or 11. <br/>
* 11 is read off as "two 1s" or 21.<br/>
* 21 is read off as "one 2, then one 1" or 1211.<br/>
* Given an integer n, generate the nth sequence.
*
* Note: The sequence of integers will be represented as a string.
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月24日 下午7:38:08
* </p>
* @version V1.0.0
*
*/
public class CountAndSay {
// 刚开始提交两次都是wrong answer,因为没有正确理解题意,该题意思是每次都是从1,开始生成序列串,只是取出排在第n个的序列串返回而已
public String countAndSay(int n) {
ArrayList<String> al = new ArrayList<String>();
al.add(String.valueOf(1));
for (int i = 0; i < n; i++) {
String generateString = generateString(al.get(i));
al.add(generateString);
}
return al.get(n - 1);
}
// 负责从1开始生成所有的序列串,直到n为止
public String generateString(String s) {
char[] charArray = s.toCharArray();
int count = 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < charArray.length - 1; i++) {
if (charArray[i] == charArray[i + 1]) {
count++;
} else {
sb.append(count);
count = 1;
sb.append(charArray[i]);
}
}
sb.append(count);
sb.append(charArray[charArray.length - 1]);
return sb.toString();
}
// Wrong Answer
// Input: 1
// Output: "11"
// Expected: "1"
public static void main(String[] args) {
String countAndSay = new CountAndSay().countAndSay(2);
System.out.println(countAndSay);
}
}
原文:http://blog.csdn.net/shijiebei2009/article/details/44598919