首页 > 学院 > 开发设计 > 正文

Count and Say

2019-11-15 01:15:51
字体:
来源:转载
供稿:网友
Count and SayCount and Say

https://leetcode.com/PRoblems/count-and-say/

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.

算法思想:

1) 可以根据当前的这个string,来计算下一个string,如“1211”,得到“one 1 one 2 two 1”,即"111221"

程序代码:
public class Solution {    public String next(String s) {        int length = s.length();        char pre = s.charAt(0);        int count = 1;        StringBuilder sb = new StringBuilder();        for (int i = 1; i < length; i++) {            if (s.charAt(i) == pre) {                count++;            } else {                sb.append(count);                sb.append(pre);                count = 1;                pre = s.charAt(i);            }        }        sb.append(count);        sb.append(pre);                return sb.toString();    }        public String countAndSay(int n) {        if (n <= 0) {            return "";        }                String cas = "1";        for (int i = 2; i <= n; i++) {            cas = next(cas);        }        return cas;    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表