Count and Say

题目来源: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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值