题目描述:
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 = 2
Output: "01"
Note: "10" will be accepted too.
Example 2:
Input: n = 2, k = 2
Output: "00110"
Note: "01100", "10011", "11001" will be accepted too.
Note:
1. n will be in the range [1, 4].
2. k will be in the range [1, 10].
3. k^n will be at most 4096.
class Solution {
public:
// The password will automatically be matched against the last n digits entered
// 意思是指输入一段密码,输入过程中有n位和密码匹配即可,不一定是整段输入的最后
string crackSafe(int n, int k) {
// 为了充分利用现有的输入,可以选取输入的后(n-1)位,然后添加[0,k-1]任意一个数,如果它不是之前出现过的密码
// 说明这样添加了一个输入字符,就可以多匹配一个密码,实现这一点只需要一个hash表做记录即可
unordered_map<string,bool> hash;
string result=string(n,'0'); // 从全0的密码开始
hash[result]=true;
for(int i=0;i<pow(k,n);i++)
{
for(int j=k-1;j>=0;j--)
{
string s=result.substr(result.size()-n+1,n-1)+to_string(j);
if(hash.count(s)==0)
{
hash[s]=true;
result+=to_string(j);
break;
}
}
}
return result;
}
};