美文网首页
38. Count and Say

38. Count and Say

作者: IELBHJY | 来源:发表于2017-11-20 23:20 被阅读0次

    题目如图


    屏幕快照 2017-11-20 下午11.15.55.png

    思路:用递归,虽然今天刚见识到递归的缺点,一会写在另外一篇文章里。
    Java代码:

    class Solution {
        public String countAndSay(int n) {
          String result="";
          if(n<=0){
              return "";
          }
          if(n==1) {
              result="1";
          }
          else{
                String temp=countAndSay(n-1);
                if(temp.length()==1){
                    return String.valueOf(1)+temp;
                }
                int k=0;
                for(int i=0;i<temp.length()-1;i++)
                {
                    if(temp.charAt(i+1)!=temp.charAt(i)){
                        result+=String.valueOf(i+1-k)+String.valueOf(temp.charAt(i));
                        k=i+1;
                    }
                }
                if(k<temp.length()){
                    result+=String.valueOf(temp.length()-k)+temp.charAt(k);
                }
          }
          return result;
        }
    }
    

    一遍提交成功,哈哈哈,不过运行时间这不好,后边还会补充好的方法吧

    相关文章

      网友评论

          本文标题:38. Count and Say

          本文链接:https://www.haomeiwen.com/subject/ndabvxtx.html