Goldman Sachs Interview Question
Financial Software DevelopersCountry: India
Interview Type: Phone Interview
Even more concise:
for (int i=0, j = 0 ;j <= strlen(input); ++j){
if(input[j] != ' ')
input[i++] = input[j];
}
Since the null terminator is also not equal to space, no need to have a special case for it.
In C++, I always tray to used a developed algorithm instead of implementing a new one. And to remove a character nothing better than std::remove algorithm.
#include <iostream>
#include <algorithm>
int main()
{
char str[] = "aab c de";
std::remove(str, str+sizeof(str)/sizeof(str[0]), ' ');
std::cout << str;
}
i am just trying it other way. let me know if i am approaching wrong way.
#include<stdio.h>
main()
{
char A[] ={'a','a','b',' ',' ','c',' ','d','e'};
int i=0;
int p=0;
int count = 0;
int length=sizeof(A)/sizeof(A[0]);
printf("Original array is:: %s\n and length of array is %d\n",A,strlen(A));
while(i<length)
{
if(A[i] == ' ')
{
if(count<1)
p = i;
count++;
}
else
{
if(count>=1)
{
A[p]=A[i];
p++;
count--;
}
}
i++;
}
A[p] = '\0';
printf("Final array is :: %s \n and legth of final string is %d\n",A,strlen(A));
getch();
}
char ch[] = new char[] { 'a', 'a', 'b', ' ', ' ', 'd', ' ', ' ', ' ',
'e', 'f', ' ' };
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ' ') {
boolean swaped = false;
for (int j = i + 1; j < ch.length; j++) {
if (ch[j] != ' ') {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
swaped = true;
break;
}
}
if (!swaped) {
break;
}
}
}
{
package my.practice.ds.puzzles;
import java.util.Arrays;
public class NextNonSpaceChar {
public static void main(String[] args) {
char ch[] = new char[] { 'a', 'a', 'b', ' ', ' ', 'd', ' ', ' ', ' ',
'e', 'f', ' ' };
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ' ') {
boolean swaped = false;
for (int j = i + 1; j < ch.length; j++) {
if (ch[j] != ' ') {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
swaped = true;
break;
}
}
if (!swaped) {
break;
}
}
}
System.out.println(Arrays.toString(ch));
}
}
}
In C# we can use this:
input = new String(input.ToString().Where(Char.IsLetter).ToArray());
Console.Write(input);
I think the C code will be Okay to remove all spaces in the string :input
- notbad July 16, 2012