码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Count and Say

时间:2016-06-02 13:51:25      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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.

思路:

题目看懂了就好做了。。

算法:

public String countAndSay(int n) {  
    String r = "1";  
    for (int i = 1; i < n; i++) {  
        String t = "";  
        int count = 0;  
        String flag = r.charAt(0) + "";  
        for (int j = 0; j < r.length(); j++) {  
            if ((r.charAt(j) + "").equals(flag)) {  
                count++;  
            } else {  
                t += count + "" + flag;  
                flag = r.charAt(j) + "";  
                count = 1;  
            }  
        }  
        t += count + "" + flag;  
        r = t;  
    }  
    return r;  
}  


【Leetcode】Count and Say

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51558595

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!