[leetcode]38. Count and Say@Java

来源:互联网 发布:svd分解 对角矩阵 编辑:程序博客网 时间:2024/05/16 14:48

https://leetcode.com/problems/count-and-say/#/description


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

1.     12.     113.     214.     12115.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1Output: "1"

Example 2:

Input: 4Output: "1211"



package go.jacob.day720;/** * 38. Count and Say *  * @author Jacob * */// 思路:n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;// n=3时,由于上次字符是11,有2个1,所以输出21;// n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。// 依次类推,写个countAndSay(n)函数返回字符串。public class Demo2 {/* * 修改后的解答,使用StringBuilder 运行时间大大缩短 Runtime: 7 ms */public String countAndSay(int n) {if (n <= 0)return "";StringBuilder res = new StringBuilder();StringBuilder pre = new StringBuilder();res.append("1");for (int i = 1; i < n; i++) {pre = res;res = new StringBuilder();int count = 1;for (int j = 1; j < pre.length(); j++) {if (pre.charAt(j) == pre.charAt(j - 1)) {count++;} else {res.append(count).append(pre.charAt(j - 1));count = 1;}}res.append(count).append(pre.charAt(pre.length() - 1));}return res.toString();}/* * My Solution.Runtime: 44 ms */public String countAndSay_1(int n) {if (n <= 0)return "";String res = "1";for (int i = 1; i < n; i++) {String tmp = "";int count = 1;for (int j = 1; j < res.length(); j++) {if (res.charAt(j) == res.charAt(j - 1)) {count++;} else {tmp = tmp + count + res.charAt(j - 1);count = 1;}}tmp = tmp + count + res.charAt(res.length() - 1);System.out.println(tmp);res = tmp;}return res;}}


原创粉丝点击