Dare2Solve
The problem requires encrypting a string s
by shifting each character k
positions forward in a cyclic manner. This means if the shift goes beyond the end of the string, it wraps around to the beginning.
Handle Edge Cases: If s
is empty or k
is 0, return s
directly since no encryption is needed.
Calculate Effective Shift: Compute the effective shift as k % len(s)
to handle cases where k
is larger than the length of s
.
Construct the Encrypted String:
c
in the string s
.c
using (current_position + effective_shift) % len(s)
.Return the Result: Once all characters are shifted, return the encrypted string.
Given s = "abcdef"
and k = 3
:
3 % 6 = 3
."defabc"
.s
. Each character in s
is processed exactly once.class Solution {
public:
string getEncryptedString(string s, int k) {
k %= s.length();
return s.substr(k) + s.substr(0, k);
}
};
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
k %= len(s)
return s[k:] + s[:k]
class Solution {
public String getEncryptedString(String s, int k) {
k %= s.length();
return s.substring(k) + s.substring(0, k);
}
}
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var getEncryptedString = function (s, k) {
k %= s.length;
return s.substring(k) + s.substring(0, k);
};