首页 > 编程语言 > 详细

Java for LeetCode 038 Count and Say

时间:2015-05-09 17:23:07      阅读:231      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!