Bloomberg LP Interview Question
Software Engineer / Developerswhen the first space after any word is encountered put ")(" then use a while loop to eat up as many whitespaces as possible(ie until the first non-whitespace character is encountered).
i = 0;
temp[j++] = '(';
while (str[i] != '\0')
{
if (str[i] == ' ')
{
while (str[i++] == ' ');
temp[j] = ')'
temp[j++] = '(';
}
else
{
temp[j++] = str[i++];
}
}
temp[j++] = ')';
temp[j] = '\0';
#include <cstdio>
#include <memory>
#include <cstdlib>
#include <cstring>
int main()
{
char arr[] = "a bc defga dcbaifk";
// Allocate enough space if there is space
// if there is space between each of the chars.
int len = strlen(arr)*3 + 1;
char * q, *p , *qstart;
p = arr;
printf(" Start p = %s\n",p);
q = (char *) malloc (sizeof(char) * len);
qstart = q;
*q = '('; q++;
while(p && *p)
{
if(*p == ' ')
{
*q = ')';
q++;
*q = '(';
}
else
{
*q = *p;
}
++q;
++p ;
}
*q = ')';
++q;
*q = '\0';
printf(" End q = %s\n",qstart);
}
host:~/testing$ ./replspc
Start p = a bc defga dcbaifk
End q = (a)(bc)(defga)(dcbaifk)
string Replace(const string& input)
{
string ret = "";
bool in_word = false;
for (int i = 0; i < input.size(); ++i) {
if (!in_word && input[i] != ' ') {
in_word = true;
ret += '(';
ret += input[i];
} else if (in_word && input[i] == ' ') {
ret += ')';
in_word = false;
} else if (in_word && input[i] != ' ') {
ret += input[i];
}
}
if (in_word) {
ret += ')';
}
return ret;
}
}
A finite automaton should work for this, which seems overkill and silly after I wrote the code :-(
2 important states, SPACE and NOTSPACE.
- Anonymous March 10, 2009