首页 > 其他 > 详细

Count and Say

时间:2014-02-27 00:19:22      阅读:498      评论: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,然后返回第n个序列,例如整数1返回“1”,读着one1;整数3返回“21”,读着two 1s;那么当取整数6,应该返回“312211”读着三个1,二个2,一个1。取整数7时,返回“13112221”。

	public String countAndSay(int n)
	{
		String str = "1";
		if(n==1)
		{
			return str;
		}
		for(int i = 2;i<=n;i++)
		{
			str = getTmp(str);
		}
		return str;
	}
	
	public String getTmp(String nstr)
	{
		String str = "";
		char tmp;
		tmp = nstr.charAt(0);
		int count = 0;
		for(int i = 0;i<nstr.length();i++)
		{
			if(nstr.charAt(i)==tmp)
			{
				count++;
			}
			else
			{
				str+=count;
				str+=tmp;
				tmp = nstr.charAt(i);
				count = 1;
			}
		}
		str+=count;
		str+=tmp;
		return str;
	}



Count and Say,布布扣,bubuko.com

Count and Say

原文:http://blog.csdn.net/cow__sky/article/details/19927969

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!