某公司门禁密码使用动态口令技术。初始密码为字符串 password
,密码更新均遵循以下步骤:
- 设定一个正整数目标值
target
- 将
password
前target
个字符按原顺序移动至字符串末尾
请返回更新后的密码字符串。
示例 1:
输入: password = "s3cur1tyC0d3", target = 4 输出: "r1tyC0d3s3cu"示例 2:
输入: password = "lrloseumgh", target = 6 输出: "umghlrlose"
提示:
1 <= target < password.length <= 10000
这道题算是困扰我有一点久了,实际上很简单。
然后就是关于数组的下标,这个地方画一下图就能解决了。
char* dynamicPassword(char* password, int target) {
int len = strlen(password);//求出密码的长度
char* updatedPassword = malloc(sizeof(char) * (len + 1));
//考虑一下字符串结尾的情况
if (updatedPassword == NULL) {
// 处理内存分配失败的情况
exit(1);
}
// 将 password 前 target 个字符按原顺序移动至字符串末尾
for(int i = 0; i < target; i++) {
updatedPassword[i+len-target] = password[i];
}
// 将剩余部分复制到新字符串中
int j = 0;
for(int i = target; i < len; i++) {
updatedPassword[j++] = password[i];
}
// 添加字符串结束符
updatedPassword[len] = '\0';
return updatedPassword;
}