38. Count and Say

    /*
     * 38. Count and Say 
     * 2016-5-2 by Mingyang 注意边界问题
     * 第一种是自己写的,虽然有点丑,但是可以用
     * 然后注意int count=0;这句话一定要在while里面用
     * 因为没执行一次while循环就必须要更新一下count
     */
     public static String countAndSay1(int n) {
            String res="";
            if(n<=0)
             return res;
            if(n==1)
               return "1";
            String temp="1";
            while(n>1){
               int count=0;
               StringBuffer sb=new StringBuffer();
               for(int i=0;i<temp.length();i++){
                  if(i!=0&&temp.charAt(i)!=temp.charAt(i-1)){
                      sb.append(count);
                      sb.append(temp.charAt(i-1));
                      count=1;
                  }else{
                      count++;
                  }
               }
               if(count!=0){
                 sb.append(count);
                 sb.append(temp.charAt(temp.length()-1));
               }
               temp=sb.toString();
               n--;
            }
            return temp;
        }
     /*
      * 这里就是网上的代码
      */
    public static String countAndSay(int n) {
        if (n <= 0)
            return "";
        String curRes = "1";// 不用单独算1
        int start = 1;// 从1开始算
        while (start < n) {
            StringBuilder res = new StringBuilder();
            int count = 1;
            for (int j = 1; j < curRes.length(); j++) {
                if (curRes.charAt(j) == curRes.charAt(j - 1))
                    count++;
                else {
                    res.append(count);
                    res.append(curRes.charAt(j - 1));
                    count = 1;
                }
            }
            // 代码写在这里很好,因为这里有两种情况需要,一种是刚开始来的时候curRes长度为1,for不执行的时候,那么只有直接加,另外一种就是
            // 加到最后一个的时候,我们需要把最后一个东西积极补上。无论如何就是加上最后一个的值
            res.append(count);
            res.append(curRes.charAt(curRes.length() - 1));
            curRes = res.toString();
            start++;
        }
        return curRes;
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5457856.html