【Leetcode】38. Count and Say

Question:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

Leedcode提交代码:Runtime: 19 ms

StringBuilder curr=new StringBuilder("1");
        StringBuilder ans;
        //if(n==1) return "1";
        int temp;
        char a;
        for(int i=1;i<n;i++){//循环n
            ans=curr;
            curr=new StringBuilder();
            temp=1;
            int length=ans.length();
            a=ans.charAt(0);
            for(int j=1;j<length;j++){//循环上一个ans

                if(ans.charAt(j)!=a){
                    curr.append(temp).append(a).toString();
                    temp=1;
                    a=ans.charAt(j);
                    //System.out.println(ans);
                }else{
                    temp++;
                }

            }
            curr.append(temp).append(a);
        }
        System.out.println(curr);
        return curr.toString();

完整可运行代码:

package easy;

public class L38 {
    public String countAndSay(int n) {
        StringBuilder curr=new StringBuilder("1");
        StringBuilder ans;
        //if(n==1) return "1";
        int temp;
        char a;
        for(int i=1;i<n;i++){//循环n
            ans=curr;
            curr=new StringBuilder();
            temp=1;
            int length=ans.length();
            a=ans.charAt(0);
            for(int j=1;j<length;j++){//循环上一个ans

                if(ans.charAt(j)!=a){
                    curr.append(temp).append(a).toString();
                    temp=1;
                    a=ans.charAt(j);
                    //System.out.println(ans);
                }else{
                    temp++;
                }

            }
            curr.append(temp).append(a);
        }
        System.out.println(curr);
        return curr.toString();
    }

    public static void main(String[] args) {
        L38 l38 = new L38();
        l38.countAndSay(9);
    }
}

注:

①最开始使用一个String变量ans进行循环,导致每轮次ans之间混乱,加入curr变量,解决这个问题。

② String与StringBuilder之间的区别:

    String:字符串常量

    StringBuffer:字符串变量

String s = "abcd";//创建名为s的String类型变量 abcd
s = s+1;//创建新的对象s 赋值为abcd1
System.out.print(s);// result : abcd1

    StringBuilder:线程非安全的

    StringBuffer:线程安全的

              1.如果要操作少量的数据用 = String

                        2.单线程操作字符串缓冲区 下操作大量数据 = StringBuilder

                        3.多线程操作字符串缓冲区 下操作大量数据 = StringBuffer

当stringBuilder全部变成String可运行代码:Runtime: 63 ms

String curr=new String("1");
        String ans;
        //if(n==1) return "1";
        int temp;
        char a;
        for(int i=1;i<n;i++){//循环n
            ans=curr;
            curr=new String();
            temp=1;
            int length=ans.length();
            a=ans.charAt(0);
            for(int j=1;j<length;j++){//循环上一个ans

                if(ans.charAt(j)!=a){
                    curr+=temp;
                    curr+=a;
                    temp=1;
                    a=ans.charAt(j);
                    //System.out.println(ans);
                }else{
                    temp++;
                }

            }
            curr+=temp;
            curr+=a;
        }
        System.out.println(curr);
        return curr;
时间: 2024-11-03 03:35:12

【Leetcode】38. Count and Say的相关文章

【leetcode】204 - Count Primes

Description:Count the number of prime numbers less than a non-negative number, n. Hint: Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity

【leetcode】357. Count Numbers with Unique Digits

题目描述: Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. 解题分析: 题目要就就是找出 0≤ x < 10n中各位数字都不相同的数的个数.要接触这道题只需要理解: 1.设f(n)表示n为数字中各位都不相同的个数,则有countNumbersWithUniqueDigits(n)=f(1)+f(2)+……+f(n)=f(n)+countNumbersWithU

【LeetCode】327. Count of Range Sum

题目: Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and  j (i ≤ j), inclusive. Note: A naive algorithm of O(n2) is tr

【LeetCode】204. Count Primes 解题小结

题目: Description: Count the number of prime numbers less than a non-negative number, n. 这个题目有提示,计算素数的方法应该不用多说. class Solution { public: int countPrimes(int n) { vector<bool> isPrime; for (int i = 0; i < n; ++i){ isPrime.push_back(true); } for (int

【LeetCode】222. Count Complete Tree Nodes

Count Complete Tree Nodes Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last le

【LeetCode】222. Count Complete Tree Nodes-完全二叉树的结点个数

一.描述: 二.思路: 完全二叉树: 对于整棵二叉树,从根结点出发,一直沿左下方向遍历树的深度是l,一直沿右下方向遍历的深度是r:则有两种情况: 1.l == r,左右深度相等,一定是完全二叉树,即满二叉树,结点个数为(2^l-1)或(2^r-1): 2.l != r,只有一种情况:在二叉树的倒数第二层,某个父结点只有左叶子结点而无右叶子结点,及l=r+1.等价的说,将这一个多余的左叶子结点去掉的话,则每棵最小的二叉树(一共3个结点)都是满二叉树,即又回到了上述情况1,最后再加1即为总叶子结点:

【LeetCode】38.报数

class Solution { public: string countAndSay(int n) { string str,ans; str="1"; if(n--==1) return str; while(n--){ ans.clear(); int left=0,right=0; while(right<str.size()){ if(str[right]==str[left]) right++; else{ ans+=(right-left+'0'); ans+=st

【leetcode】1395. Count Number of Teams

题目如下: There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rat

【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 递归和非递归,此提比较简单.广度优先遍历即可.关键之处就在于如何保持访问深度. 下面是4种代码: 1