Input: s ="dart", k =3Output: "tdar"Explanation:
* For `i = 0`, the 3rd character after `'d'`is`'t'`.* For `i = 1`, the 3rd character after `'a'`is`'d'`.* For `i = 2`, the 3rd character after `'r'`is`'a'`.* For `i = 3`, the 3rd character after `'t'`is`'r'`.
To encrypt the string, for each character at index i, we replace it with the character at index (i + k) % n, where n is the length of the string. This wraps around the string in a cyclic manner.
classSolution {
public String encryptString(String s, int k) {
int n = s.length();
char[] ans =newchar[n];
for (int i = 0; i < n; ++i) {
ans[i]= s.charAt((i + k) % n);
}
returnnew String(ans);
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funencryptString(s: String, k: Int): String {
val n = s.length
val ans = CharArray(n)
for (i in0 until n) {
ans[i] = s[(i + k) % n]
}
return String(ans)
}
}
1
2
3
4
classSolution:
defencryptString(self, s: str, k: int) -> str:
n = len(s)
return''.join(s[(i + k) % n] for i in range(n))
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnencrypt_string(s: String, k: i32) -> String {
let n = s.len();
let s = s.as_bytes();
letmut ans =vec![0u8; n];
for i in0..n {
ans[i] = s[(i + k asusize) % n];
}
String::from_utf8(ans).unwrap()
}
}