LeedCode 之 Count and Say

来源:互联网 发布:怎么投诉淘宝店 编辑:程序博客网 时间:2024/06/18 05:00

写在前面:前两天有些事情耽误了,没能每天一天,昨天晚上这道题目在实验室的电脑上写完了的,但是好像忘记保存了还是怎么的,就没能留下来,无奈今天又实现了遍,正好检验下是否只能能够完成这道题~


题目链接:Count and Say
这道题目看了半天也不知道应该怎么处理,按道理应该是n取不同值的时候,数字序列存在不同的规律,但是始终没发现是什么规律,只得在网上查看了下其他的想法的解法。

题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211,以此类推。

public class Solution {    public String oneString(String str){        int len = str.length();        int count = 0;        char index = str.charAt(0);        String newstr = new String();        for(int i=0;i<len;i++){            if(str.charAt(i)==index)                count++;            else            {                newstr = newstr+Integer.toString(count)+index;                index = str.charAt(i);                count=1;            }            if(i==len-1)                newstr = newstr+Integer.toString(count)+index;        }        return newstr;    }    public String countAndSay(int n) {        String result = new String();        result = "1";        if(n==1)            return result;//首先对n=1的情况进行处理        for(int i=1;i<n;i++)            result = oneString(result);        return result;    }}
0 0
原创粉丝点击