38. Count and Say

来源:互联网 发布:双翼软件官网 编辑:程序博客网 时间:2024/06/17 21:08

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" or11.
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个数;这种序列每一个数都是前面数的特殊读法,从1开始逐渐依次求解即可.

时间复杂度: O(N*N)

public String countAndSay(int n) {        if(n<=0)            return "";        else if(n==1)            return "1";        String st="1";        int num;        char c;        while(n>1){            num=1;            String temp="";            c=st.charAt(0);            for(int i=1;i<st.length();i++){                if(c==st.charAt(i))                    num++;                else{                    temp+=num+""+c;                    c=st.charAt(i);                    num=1;                }            }            temp+=num+""+c;            st=temp;            n--;        }        return st;    }


0 0
原创粉丝点击