码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 038 Count and Say

时间:2015-05-09 17:25:14      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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);
			}
			else
				count++;
		}
		sb.append(count);
		sb.append(temp);
		return sb.toString();
	}

 

Java for LeetCode 038 Count and Say

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4490638.html

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