Amazon Interview Question
Software EngineersCountry: United States
using System.Collections.Generic;
using System.Linq;
using System;
public class Obj{
public int reIndex;
public string a;
public string b;
public Obj(int ind, string a, string b){
reIndex = ind;
this.a = a;
this.b = b;
}
}
public class IndexReplace{
public string ReplaceIndx(string str, List<Obj> obj)
{
int offset = 0;
foreach (var a in obj)
{
if (str.IndexOf(a.a) != -1)
{
if (offset > 0)
{
str = str.Remove(a.reIndex-offset, a.a.Length);
str = str.Insert(a.reIndex-offset, a.b);
}
else if (offset < 0)
{
str = str.Remove(a.reIndex+ Math.Abs(offset), a.a.Length);
str = str.Insert(a.reIndex + Math.Abs(offset), a.b);
}
else {
str = str.Remove(a.reIndex, a.a.Length);
str = str.Insert(a.reIndex, a.b);
}
offset +=a.a.Length - a.b.Length;
}
}
return str;
}
public static void Main(string[] args){
string str = "Hello world!";
List<Obj> list = new List<Obj>();
list.Add(new Obj(0,"Hello","Goodbye"));
list.Add(new Obj(11,"!","?"));
list.Add(new Obj(6,"world","friend"));
IndexReplace iR = new IndexReplace();
Console.WriteLine("Input String:"+ str);
Console.WriteLine(iR.ReplaceIndx(str, list));
}
}
target = "Hello world!"
- Anonymous May 09, 2018ins = [{"s":0,"a":"Hello","b":"Goodbye"},{"s":11,"a":"!","b":"?"},{"s":6 ,"a":"World","b":"friend"}]
result = target
for i in ins:
offset = len(result) - len(target)
s = i["s"] + offset
l = s + len(i["a"])
result = result[:s] + i["b"]+ result[l:]
print(result)