Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
public static String removeWhenOccurMoreThanOne(String target){
char [] ch=target.toCharArray();
int end=0;
boolean bSwitch=true;
for (int i=0;i<target.length();++i){
if (ch[i]!=' '){
ch[end]=ch[i];
bSwitch=true;
end++;
}else if (ch[i]==' '&&bSwitch){
end++;
bSwitch=false;
}
}
return new String(ch,0,end);
}
public class TrimSpaces {
public static void main(String str[]){
String stri = "lohith is a developer";
System.out.println(stri.length());
char array[] = stri.toCharArray();
int index=-1,end=-1;
for(int i=0;i<array.length;i++){
if(array[i]==' '){
if(index==-1){
index=i;
}else{
end=i;
}
}else{
if(index !=-1 && end !=-1 ){
shiftStringAcrossSpaceFrom(index,end,array);
System.out.println(index + " index & end ="+end+" array="+new String(array));
i=index+1;
index=-1;end=-1;
}
}
}
}
private static void shiftStringAcrossSpaceFrom(int index, int endIndex,
char[] strichar) {
int j=0;
for(int i=endIndex;i<strichar.length;i++,j++)
strichar[index+j] = strichar[i];
int skipped =endIndex-index;
strichar[strichar.length - skipped] = '\0';
for(int i=strichar.length - skipped ; i <strichar.length ;i++){
strichar[i] = '\0';
}
}
}
class RemoveSpaces
{
public static void RemoveSpaces(String ip)
{
String output = "";
int i=0;
while(i<ip.length())
{
if(ip.charAt(i)!= ' ')
{
output+=ip.charAt(i);
}
else
{
if(ip.charAt(i+1)!=' ')
output+=ip.charAt(i);
}
i++;
}
System.out.println(output);
}
public static void main(String args[])
{
String input = "I am Awe some";
RemoveSpaces(input);
}
}
Why are everyone moving the spaces to the end of the string?
Instead of using a Char array, we can directly use a String - dynamic data structure.
Can someone correct me if I am wrong.
I will assume the problem is to make an in-place modification.
- Anonymous May 04, 2012