leetcode [Count and Say]

来源:互联网 发布:比特币挖矿程序 mac 编辑:程序博客网 时间:2024/05/16 17:01
class Solution{/*题意是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 String countAndSayPrepare(String Str) {        String res = "";        int count = 1;        char temp = Str.charAt(0);        for(int i = 1; i < Str.length(); i++){        if(Str.charAt(i) == temp) count++;        else{        res += "" + count + temp;        //存完后修改信息        temp = Str.charAt(i);        count = 1;        }        }        res += "" + count + temp;//最后装上跳出字符串存下的东西        return res;    }        public String countAndSay(int n) {    String res = "1";    for(int i = 1; i < n; i++){    res = countAndSayPrepare(res);    }    return res;    }}

0 0
原创粉丝点击