3.5 leet38

2019-03-15  本文已影响0人  反复练习的阿离很笨吧
  1. Count and Say
    思路:
    1 第一个for,数序列
    2 第二个for,用来读这一项,计算出下一项
class Solution {
    public String countAndSay(int n) {       
        String a=new String("1");        
        for(int i=1;i<n;i++)
        {
            String res=new String("");
            a=a+'0';
            int count=1;
            for(int j=0;j<a.length()-1;j++)
            {
                if(a.charAt(j)==a.charAt(j+1))
                {
                    count++;
                }
                else
                {
                    res=res+count+a.charAt(j);
                    count=1;
                }                
            }
            a=res;
        }
        return a;
    }
}

遇到在循环里要用到i和i+1的时候,总是会碰到溢出的问题,不知道怎么解决。在这题里机智的我在字符串最末加了一个字符,对结果没影响,也不会溢出了。

上一篇 下一篇

猜你喜欢

热点阅读