753. Cracking the Safe

网友投稿 568 2022-11-11

753. Cracking the Safe

753. Cracking the Safe

There is a box protected by a password. The password is n digits, where each letter can be one of the first k digits 0, 1, …, k-1.

You can keep inputting the password, the password will automatically be matched against the last n digits entered.

For example, assuming the password is “345”, I can open it when I type “012345”, but I enter a total of 6 digits.

Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted.

Example 1:

Input: n = 1, k = 2Output: "01"Note: "10" will be accepted too.

Example 2:

Input: n = 2, k = 2Output: "00110"Note: "01100", "10011", "11001"

Note: n will be in the range [1, 4]. k will be in the range [1, 10]. k^n will be at most 4096.

class Solution { public String crackSafe(int n, int k) { int M = (int) Math.pow(k, n-1); int[] P = new int[M * k]; for (int i = 0; i < k; ++i) for (int q = 0; q < M; ++q) P[i*M + q] = q*k + i; StringBuilder ans = new StringBuilder(); for (int i = 0; i < M*k; ++i) { int j = i; while (P[j] >= 0) { ans.append(String.valueOf(j / M)); int v = P[j]; P[j] = -1; j = v; } } for (int i = 0; i < n-1; ++i) ans.append("0"); return new String(ans); }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:749. Contain Virus
下一篇:757. Set Intersection Size At Least Two
相关文章

 发表评论

暂时没有评论,来抢沙发吧~