We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I solved it slightly differently using Typescript. I created a dictionary that will have the original letter as the key and then the rotated letter as the value. I then iterate over the string and map that char to the dictionary and check for special chars or uppercase (regex) into a new string
`
function caesarCipher(s: string, k: number): string {
// Write your code here
const alph = 'abcdefghijklmnopqrstuvwxyz'
const dic: Dictionary = {}
for (let i = 0; i < alph.length; i++) {
const rotated = (i + k) % 26
dic[alph[i]] = alph[rotated]
}
let decypher = ''
let pattern = /[A-Z]/g;
for (let i = 0; i< s.length; i++) {
// check for uppercase
if (s[i].match(pattern)) {
const lower = dic[s[i].toLowerCase()]
decypher += lower.toUpperCase()
} else {
// if in dictionary add the value else add the original special char
decypher += dic[s[i]] ?? s[i]
}
}
return decypher
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Caesar Cipher
You are viewing a single comment's thread. Return to all comments →
I solved it slightly differently using Typescript. I created a dictionary that will have the original letter as the key and then the rotated letter as the value. I then iterate over the string and map that char to the dictionary and check for special chars or uppercase (regex) into a new string
` function caesarCipher(s: string, k: number): string { // Write your code here const alph = 'abcdefghijklmnopqrstuvwxyz' const dic: Dictionary = {} for (let i = 0; i < alph.length; i++) { const rotated = (i + k) % 26 dic[alph[i]] = alph[rotated] }
}