Solving Strings Problems - AlgoExpert

1. Caesar Cipher Encryptor

Python

# O(n) time | O(n) space
def caesarCipherEncryptor(string, key):
    newKey = key % 26
  result = []
  for char in string:
    ascii_ = ord(char) + newKey
    if ascii_ <= 122:
      result.append(chr(ascii_))
    else:
      result.append(chr(96 + ascii_ % 122))
  return "".join(result)


# O(n) time | O(n) space
#import string
def caesarCipherEncryptor(string, key):
    # string.ascii_lowercase
  # >> abcdefghijklmnopqrstuvwxyz
    fullChar = list("abcdefghijklmnopqrstuvwxyz")
  newKey = key % 26
  result = []
  for char in string:
    newLetterCode = fullChar.index(char) + newKey
    if newLetterCode <= 25:
      result.append(fullChar[newLetterCode])
    else:
      result.append(fullChar[newLetterCode % 26])
  return "".join(result)
      

2. Run-length Encoding

Python

# O(n) time | O(n) space
def caesarCipherEncryptor(string, key):
    newKey = key % 26
  result = []
  for char in string:
    ascii_ = ord(char) + newKey
    if ascii_ <= 122:
      result.append(chr(ascii_))
    else:
      result.append(chr(96 + ascii_ % 122))
  return "".join(result)


# O(n) time | O(n) space
#import string
def caesarCipherEncryptor(string, key):
    # string.ascii_lowercase
  # >> abcdefghijklmnopqrstuvwxyz
    fullChar = list("abcdefghijklmnopqrstuvwxyz")
  newKey = key % 26
  result = []
  for char in string:
    newLetterCode = fullChar.index(char) + newKey
    if newLetterCode <= 25:
      result.append(fullChar[newLetterCode])
    else:
      result.append(fullChar[newLetterCode % 26])
  return "".join(result)
      
Avatar
comments powered by Disqus

Related

© 2018-2021 Harry Trinh. All thoughts and opinions here are my own. Powered by the Academic theme for Hugo.