[Leetcode学习-c++&java]Count and Say

46 篇文章 0 订阅

问题:

难度:medium

说明:

首先第一个数字是 1。

然后开始进行游程编码:11,意思是 1 个 1

下一步继续游程编码:21,意思是 2 个 1

继续: 1211 意思是 1 个 2 ,1 个 1

求第 N 步的结果是多少

题目连接:https://leetcode.com/problems/count-and-say/

输入范围:

  • 1 <= n <= 30

输入案例:

Example 1:
Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

我的代码:

只是游程编码罢了,然后就是多次游程而已:

Java:

class Solution {
    private static int[][] stack = new int[2][5000]; 
    public String countAndSay(int n) {
        int pre = 1, cur = 0, idx1 = 0, idx2 = 0;
        stack[cur][idx1 ++] = 1;
        while(n -- > 1) {
            for(int i = 0; i < idx1;) {
                int tmp = stack[cur][i], cnt = 0;
                while(i < idx1 && stack[cur][i] == tmp) {
                    i ++; cnt ++;
                }
                stack[pre][idx2 ++] = cnt;
                stack[pre][idx2 ++] = tmp;
            }
            pre ^= 1;
            cur ^= 1;
            idx1 = idx2;
            idx2 = 0;
        }
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < idx1; i ++) builder.append(stack[cur][i]);
        return builder.toString();
    }
}

C++:

int twoQueue[2][5000];

class Solution {
public:
    string countAndSay(int n) {
        int cur = 0, pre = 1, idx1 = 0, idx2 = 0;
        twoQueue[cur][idx1 ++] = 1;
        while(n -- > 1) {
            for(int i = 0; i < idx1;) {
                int tmp = twoQueue[cur][i], cnt = 0;
                while(i < idx1 && twoQueue[cur][i] == tmp) {
                    i ++; cnt ++;
                }
                twoQueue[pre][idx2 ++] = cnt;
                twoQueue[pre][idx2 ++] = tmp;
            }
            pre ^= 1;
            cur ^= 1;
            idx1 = idx2;
            idx2 = 0;
        }
        
        string res = "";
        for(int i = 0; i < idx1; i ++) {
            res += to_string(twoQueue[cur][i]);
        }
        
        return res; 
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值