Algorithms—38.Count and Say

原创 2015年07月08日 09:04:47

思路:掌握规则,逐次去读书,循环N次即可。

public class Solution {
    public String countAndSay(int n) {
		if (n == 1) {
			return "1";
		}
		String answer = "1";
		for (int i = 0; i < n - 1; i++) {
			answer = new Solution().readNum(answer);
		}
		return answer;
	}

	public String readNum(String num) {
		int n = 1;
		String t = num.substring(0, 1);
		StringBuffer answer=new StringBuffer();
		String k = "";
		for (int i = 1; i < num.length(); i++) {
			k = num.substring(i, i + 1);
			if (k.equals(t)) {
				n++;
			} else {
				answer=answer.append(n).append(t);
				t = k;
				n = 1;
			}
		}
		answer = answer.append(n).append(t);
		return answer.toString();
	}
}


耗时:232ms,勉强中上游,此次测试了下用StringBuffer代替String有效的提高了效率,感觉好无趣。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LEETCODE】38-Count and Say

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221...

leetcode38 Count and Say

package leetcode38; import java.util.ArrayList; /** * The count-and-say sequence is the sequence ...

LeetCode 38 Count and Say(计数与报数)

翻译计数报数序列按如下规律开始递增: 1,11,21,1211,111221,……1 读作“1个1”或11. 11 读作“2个1”或21. 21 读作“1个2,1个1”或1211.给定一个整数n,生成...
  • NoMasp
  • NoMasp
  • 2015-12-03 10:32
  • 3650

LeetCode 38. Count and Say

问题描述: The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211...

LeetCode 38 Count and Say(字符串生成)

The count-and-say sequence is the sequence of integers with the first five terms as following: 1. ...

38. Count and Say

/* The count-and-say sequence is the sequence of integers with the first five terms as following: 1....

【leetcode c++】38 Count and Say

Count and Say The count-and-say sequence is the sequenceof integers beginning as follows: 1, 11, 2...
  • hqq39
  • hqq39
  • 2015-06-26 22:40
  • 309

Leetcode - 38. Count and Say

38. Count and Say题目简介 The count-and-say sequence is the sequence of integers beginning as follows:...

leetcode 38:count and say

问题描述:The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, ...

LeetCode 38 Count and Say(C,C++,Java,Python)

Problem: The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 2...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)