zoukankan      html  css  js  c++  java
  • LeetCode 38. Count and Say

    原题链接在这里:https://leetcode.com/problems/count-and-say/

    题目:

    The count-and-say sequence is the sequence of integers beginning as follows:
    1, 11, 21, 1211, 111221, ...

    1 is read off as "one 1" or 11.
    11 is read off as "two 1s" or 21.
    21 is read off as "one 2, then one 1" or 1211.

    Given an integer n, generate the nth sequence.

    Note: The sequence of integers will be represented as a string.

    题解:

    后一个结果是在前一个基础上得出的,采用pre 和 cur替换. 

    当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个.

    计算相同char的个数先append进去.

    Time Complexity: O(n * cur.length()). Space: O(cur.length()).

    AC Java:

     1 class Solution {
     2     public String countAndSay(int n) {
     3         if(n <= 0){
     4             return "";
     5         }
     6         
     7         StringBuilder sb = new StringBuilder("1");
     8         for(int k = 1; k<n; k++){
     9             String pre = sb.toString();
    10             sb = new StringBuilder();
    11             int count = 1;
    12             for(int i = 1; i<pre.length(); i++){
    13                 if(pre.charAt(i) == pre.charAt(i-1)){
    14                     count++;
    15                 }else{
    16                     sb.append(count);
    17                     sb.append(pre.charAt(i-1));
    18                     count = 1;
    19                 }
    20             }
    21             
    22             sb.append(count);
    23             sb.append(pre.charAt(pre.length()-1));
    24         }
    25         
    26         return sb.toString();
    27     }
    28 }
  • 相关阅读:
    自动生成四则运算题目
    学习进度总结随笔
    作业1
    软件工程项目总结
    结对编程项目---四则运算
    作业三
    自动生成小学四则运算题目的程序
    学习进度总结
    大三下自我简介
    寒假社会实*报告
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824936.html
Copyright © 2011-2022 走看看