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

[LeetCode 38] Count and Say

时间:2015-03-22 09:10:31      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   算法   

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

public class CountandSay {

//	18 / 18 test cases passed.
//	Status: Accepted
//	Runtime: 273 ms
//	Submitted: 2 minutes ago

	
    static String countAndSay(int n) {
        String s = "1";
    	for (int i = 1; i < n; i++) 
			s = countAndSay(s);
        return s;
    }
    static String countAndSay(String str) {    	
    	String say = "";
    	int count = 1;
    	for (int i = 0; i < str.length() - 1; i++) {
			if(str.charAt(i) == str.charAt(i + 1)) count++;
			else {
				say  += count + "" + str.charAt(i);
				count = 1;
			}
		}
		say  += count + "" + str.charAt(str.length() - 1);
		return say;
    }
	public static void main(String[] args) {
		System.out.println(countAndSay(4));
	}

}


[LeetCode 38] Count and Say

标签:java   leetcode   算法   

原文地址:http://blog.csdn.net/ever223/article/details/44524749

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