%20fy the string

Given a string1, replace all spaces with %20. Assume that the string has sufficient space at the end to hold additional characters. Also, the “true” length of the string is given. Make sure the space occupied is constant.

Example

1
2
Input:  "Mr John Smith    ", 13
Output: "Mr%20John%20Smith"

Solution

Complexity:

Because the question says that we have some buffer in the end of the string, and we are given the “true” length of the string, we can start from the end, and move every character from the “true” end to the string end. If we encounter a space, we place a %20 instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def percent_twentyfy(st, n):
  assert type(st) == bytearray # `isinstance` would be better
  idx = len(st) - 1 # The end of the string
  jdx = n-1 # The "true" end of the string
  while idx >= 0 and jdx >= 0:
    if st[jdx] == ord(' '):
      st[idx] = '0'
      st[idx-1] = '2'
      st[idx-2] = '%'
      idx -= 3
    else:
      st[idx] = st[jdx]
      idx -= 1
    jdx -= 1

This is a test test

  1. If you do it in Python: because strings in python are not mutable, assume that the input is a bytearray 

Zafar

Zafar
I am a 5th year PhD student at Boston University, working towards my degree in Computer Engineering. While my work focuses on digital design,error mitigation, and machine learning, my non-work interests range widely from information theory (go Shannon!), quantum computing, grandfather paradox, Star Trek, Little Mermaid, 'why is the grass green?', 1Q84, etc., etc., etc. If you want to talk about, well, anything - just ping me.

String Compression

Implement a method to perform string compression using the counts of repeated characters. If the "compressed" string would not become sma...… Continue reading

String Permuations

Published on December 01, 2016

Reverse String

Published on December 01, 2016