Problem
You are given a string s and an integer k. Encrypt the string using the following algorithm:
- For each character
cins, replacecwith thekthcharacter aftercin the string (in a cyclic manner).
Return the encrypted string.
Example 1:
Input: s = “dart”, k = 3
Output: “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'.
Example 2:
Input: s = “aaa”, k = 1
Output: “aaa”
Explanation:
As all the characters are the same, the encrypted string will also be the same.
Constraints:
1 <= s.length <= 1001 <= k <= 104sconsists only of lowercase English letters
Solution
First attempt : Time complexity O(n)
impl Solution {
pub fn get_encrypted_string(s: String, k: i32) -> String {
let len = s.len() as i32;
let chars: Vec<char> = s.chars().collect();
let mut encrypted_chars = vec![' '; len as usize];
for i in 0..len {
let new_index = (i + k) % len;
encrypted_chars[i as usize] = chars[new_index as usize];
}
encrypted_chars.into_iter().collect()
}
}
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.