Algorithms, Blockchain and Cloud

Codeforces: B. Internet Address


The problem is from codeforces: http://www.codeforces.com/problemset/problem/245/B

It is an easy string-matching related problem. You can have many ways to solve this. Because of the limitation, i.e. the first letter must be ‘h’ or ‘f’ depending on the protocol, the domain must be ‘.ru’, it is not very difficult.

Some tests are tricky. For example, there must be characters before ‘.’

For the test httpruhhphhhpuhruruhhpruhhphruhhru

The output must not be http://.ru/hhphhhpuhruruhhpruhhphruhhru because it is an invalid domain (nothing before dot)

In this case, we can put a number check, once any character is encountered, we can use the next ‘.ru’.

#!/usr/bin/env python
# codingforspeed.com
# http://www.codeforces.com/problemset/problem/245/B

from sys import stdin

s = stdin.readline().strip()

j = 3
if s[0] == 'h':
    j = 4

i = j
k = 0
while i < len(s):
    if k > 0 and s[i] == 'r' and s[i + 1] == 'u':
        break
    i += 1
    k = 1

if i + 2 == len(s):
    print s[:j] + "://" + s[j:i] + ".ru"
else:
    print s[:j] + "://" + s[j:i] + ".ru/" + s[i+2:]

The Python provides easy string manipulation e.g. s[i:j], s[:i], and s[j:], all are very straightforward, getting slices given indices of the string.

The other Python solutions are shorter, and some of them are based on regular expression.

a,b,c = raw_input().partition('tp')
d,e,f = c.rpartition('ru')
if f: e+='/'
print a+b+'://'+d+'.'+e+f

Or

s=raw_input()
n=len(s)
res = ''
for p in ['http','ftp']:
  if s.startswith(p):
    res = p+'://'
    s = s[len(p):]
    break
i=s.find('ru',1)
domain = s[:i]
res+=domain+'.ru'
s=s[i+2:]
if s:
  res += '/'+s
print res

Or

s=raw_input()
if 'http' in s and s.index('http')==0:
    first = len('http')
else:
    first = len('ftp')
second = s.rfind('ru')
s= s[:first]+'://'+s[first:second]+'.'+'ru'+'/'+s[second+2:]
if s[-1]=='/':
    print s[:-1]
else:
    print s

Or

import re;print re.sub("(?P(http)|(ftp))(?P[a-z]+)(?Pru)(?P()|(?P[a-z]+))(?P(?(realcontent)/|))/?$","\g://\g.\g\g\g",raw_input()+"/")

Or

import sys
STR = raw_input ()
if (STR[0] == 'h'):
    s = "http"
else:
    s = "ftp"
sys.stdout.write(s+"://")

f = STR.rfind ("ru")
sys.stdout.write(STR[len(s):f] + ".ru")
if not (f+2==len(STR)):
    sys.stdout.write("/" + STR[2+f:len(STR)])

Or

import re
a = raw_input()
p = re.compile('(http|ftp)(.+?)ru(.*)')
m = p.match(a)
ret = '%s://%s.ru'%m.groups()[:2]
if m.groups()[2]:
  ret += '/' + m.groups()[2]
print ret

–EOF-

535 words
Last Post: Faster PI Computation
Next Post: Quick Demonstration of Quick Sort in Python

The Permanent URL is: Codeforces: B. Internet Address (AMP Version)

Exit mobile version