Amazon Interview Question
Applications DevelopersCountry: India
Interview Type: Phone Interview
Approach is correct...
But I think you have not used the correct variables at correct places... :P
I think it should have been following instead:
str[newLength - 3] = ‘0’;
str[newLength - 2] = ‘2’;
str[newLength - 1] = ‘%’;
#include<stdio.h>
#include<string.h>
int main()
{
char a[50],b[50];
int len,i,j,spacecount=0;
gets(a);
len=strlen(a);
//printf("%d",spacecount);
for(i=0;i<len;i++)
{
if(a[i]==' ')
{
spacecount++;
}
}
j=len-1;
len=len+2*spacecount;
b[len]='\0';
i=len-1;
while(i>=0&&j>=0)
{
if(a[j]==' ')
{
b[i--]='0';
b[i--]='2';
b[i--]='%';
j--;
}
else
{
b[i--]=a[j--];
}
}
puts(b);
return 0;
}
private void encode(char[] word)
{
char[] spaceArr = { '%', '2', '0' };
for (int i = 0; i < word.length; i++)
{
if (word[i] == ' ')
{
System.arraycopy(word, i + 1, word, i + spaceArr.length, getWordLength(word)-i);
System.arraycopy(spaceArr, 0, word, i, spaceArr.length);
}
}
}
private int getWordLength(char[] word)
{
for (int i = 0; i < word.length; i++)
{
if (word[i] == '\0')
{
return i - 1;
}
}
return 0;
}
This is a known problem and available in CareerCup book:
1. Count the number of spaces during the first scan of the string.
2. Parse the string again from the end and for each character:
»»If a space is encountered, store “%20”.
»»Else, store the character as it is in the newly shifted location.
- Dilbert Einstein May 12, 2013