Lettcode_38_count-and-say的另一种错误理解

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41257397

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.

今天OJ可好几次,提交好几次都出错,最后才发现是自己把题目理解错了,回头想想就觉得好笑。

题目的意思是给定一个整数n,让你求出按照上面规律在执行若干次后所得到的串,其实该算法主要用到递归的思想。

例如n=1时输出“1”,n=2时输出“2”......


我却把题目意思错误地理解为:对于给定的整数n,对该整数n执行N次上述递归操作后得到的串。例如给定2,得到的结果是1112。

当我将给定整数设定为1000时,果断出现内存泄露,想想就觉得可怕。

按照:“对于给定的整数n,对该整数n执行N次上述递归操作后得到的串”的算法描述如下所示:

public class TestCountAndSay {
	private static String countAndSay;
	
	public static void main(String[] args) {
		countAndSay = countAndSay(12);
		System.err.println(countAndSay);
	}
	
	public static  String countAndSay(int n) {
		String value = String.valueOf(n);
		for (int i = 0; i < n; i++) {
			value = getAllSays(value);
		}
		return value;
       }

	public  static String getAllSays(String value){
		StringBuffer buffer = new StringBuffer();
		int len = value.length();
		int pos = 0;
		int max = 1;
		for (int i = 1; i <=len;i++ ) {
			if(i<len && (int)value.charAt(i) == (int)value.charAt(pos)){
				max++;
				continue;
			}else{
				buffer.append(String.valueOf(max));
				buffer.append(value.charAt(pos));
				pos = i;
				max = 1;
			}
			
		}
		return buffer.toString();
	}
}

题目真正的解法如下所示:

	public static String countAndSay(int n) {
		if (n == 1) return "1";
		String s = "1";
		StringBuffer buffer = new StringBuffer();
		//记录重复的值
		int count = 0;
		// 迭代次数
		int round = 0;
		int i;
		while (++round < n) {
			count = 1;
			buffer.setLength(0);
			for (i = 1; i < s.length(); i++) {
				// 重复的值,继续计数
				if (s.charAt(i) == s.charAt(i - 1)) { 
					count++;
				} else {
					 // 有新的值出现,记录到buffer
					buffer.append(count).append(s.charAt(i - 1));
					// 重置count
					count = 1; 
				}
			}
			buffer.append(count).append(s.charAt(i - 1));
			// 更新s
			s = buffer.toString(); 
		}
		return buffer.toString();
	}

你可能感兴趣的:(Lettcode_38_count-and-say的另一种错误理解)