算法leetcode|38. 外观数列(多语言实现)



38. 外观数列:

给定一个正整数 n ,输出外观数列的第 n 项。

「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。

你可以将其视作是由递归公式定义的数字字符串序列:

  • countAndSay(1) = "1"
  • countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。

前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221
第一项是数字 1 
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"

描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。

例如,数字字符串 “3322251” 的描述如下图:

样例 1:

输入:

	n = 1
	
输出:

	"1"
	
解释:

	这是一个基本样例。

样例 2:

输入:

	n = 4
	
输出:

	"1211"
	
解释:

	countAndSay(1) = "1"
	countAndSay(2) = 读 "1" = 一 个 1 = "11"
	countAndSay(3) = 读 "11" = 二 个 1 = "21"
	countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"

提示:

  • 1 <= n <= 30

分析:

  • 面对这道算法题目,二当家的再次陷入了沉思。
  • 很明显需要循环或者递归,模拟题意即可。
  • 由于题目规定的参数取值范围很有限(1 <= n <= 30),打表可以高效通关,没什么技术含量,但是可以应试。
  • 关键是判断当前数是否和前面数相等,计数和重置计数。
  • 需要三层循环,最外层是参数 n 次循环,第二层是对一个序列项的描述,第三层用来计数连续相同数字字符。

题解:

rust

impl Solution {
    pub fn count_and_say(n: i32) -> String {
        let mut ans = vec![b'1'];

        (2..n + 1).for_each(|i| {
            let mut cur = Vec::new();
            let mut start = 0;
            let mut pos = 0;

            while pos < ans.len() {
                while pos < ans.len() && ans[pos] == ans[start] {
                    pos += 1;
                }
                cur.push((pos - start) as u8 + b'0');
                cur.push(ans[start]);
                start = pos;
            }
            
            ans = cur;
        });

        return String::from_utf8(ans).unwrap();
    }
}

go

func countAndSay(n int) string {
    ans := "1"

	for i := 2; i <= n; i++ {
		cur := &strings.Builder{}

		for pos, start := 0, 0; pos < len(ans); start = pos {
			for pos < len(ans) && ans[pos] == ans[start] {
				pos++
			}
			cur.WriteString(strconv.Itoa(pos - start))
			cur.WriteByte(ans[start])
		}

		ans = cur.String()
	}

	return ans
}

c++

class Solution {
public:
    string countAndSay(int n) {
        string ans = "1";

        for (int i = 2; i <= n; ++i) {
            string cur = "";
            int start = 0;
            int pos = 0;

            while (pos < ans.size()) {
                while (pos < ans.size() && ans[pos] == ans[start]) {
                    ++pos;
                }
                cur += to_string(pos - start) + ans[start];
                start = pos;
            }

            ans = cur;
        }

        return ans;
    }
};

python

class Solution:
    def countAndSay(self, n: int) -> str:
        ans = "1"

        for i in range(n - 1):
            cur = ""
            pos = 0
            start = 0

            while pos < len(ans):
                while pos < len(ans) and ans[pos] == ans[start]:
                    pos += 1
                cur += str(pos - start) + ans[start]
                start = pos

            ans = cur

        return ans


java

class Solution {
    public String countAndSay(int n) {
        String ans = "1";

        for (int i = 2; i <= n; ++i) {
            StringBuilder sb    = new StringBuilder();
            int           start = 0;
            int           pos   = 0;

            while (pos < ans.length()) {
                while (pos < ans.length() && ans.charAt(pos) == ans.charAt(start)) {
                    pos++;
                }
                sb.append(Integer.toString(pos - start)).append(ans.charAt(start));
                start = pos;
            }

            ans = sb.toString();
        }

        return ans;
    }
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二当家的白帽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值