Microsoft Interview Question
Software Engineer / DevelopersYour guess is wrong..
Modified the above solution
#define SPECIAL_CHAR '!'
void reverseWords(char str[]) {
if (!str) return;
int cur=0;
int start=0;
while (str[cur]) {
if (str[cur]==SPECIAL_CHAR || str[cur]==' ') {
reverse(str, start, cur-1);
start=cur+1;
}
cur++;
}
return;
}
void reverse(char *str, int beg, int end) {
while (beg < end) {
char temp = str[beg];
str[beg] = str[end];
str[end] = temp;
beg++; end--;
}
return;
}
Right Solution --Ignore above solution
#define SPECIAL_CHAR '!'
void reverseWords(char str[]) {
if (!str) return;
int cur=0, start=0;
while (str[cur]) {
if (str[cur]==SPECIAL_CHAR || str[cur]==' ') {
if(str[cur]=SPECIAL_CHAR
cur=cur-1;
reverse(str, start, cur);
start=cur+1;
}
cur++;
}
}
void reverse(char *str, int beg, int end) {
while (beg < end) {
char temp = str[beg];
str[beg] = str[end];
str[end] = temp;
beg++; end--;
}
}
bool convert(char* str)
{
if(!str||!*str) return false;
char *p1=str;
while(*p1=='!'||*p1==' ') p1++;
char *p2=p1+1;
while(*p1)
{
while(*p2!=' '&&*p2!='!'&&*p2!='\0')
p2++;
rev(p1,p2-1);
while(*p2==' '||*p2=='!')
p2++;
p1=p2;
}
return true;
}
rev(char* p1, char* p2)
{
while(p1<p2)
{
char temp=*p1;
*p1=*p2;
*p2=temp;
p1++;p2--;
}
}
I am guessing the special char '!' is used as a pivot for reversing the words before and after it. i.e. ABCD E!FG HI! => E DCBA!IH GF!
- nunbit romance June 11, 2007This is similar to the conventional reverseWord problem.
#define SPECIAL_CHAR '!'
void reverseWords(char str[]) {
if (!str) return;
int cur=0;
int start=0;
while (str[cur]) {
if (str[cur]==SPECIAL_CHAR) {
reverse(str, start, cur-1);
start=cur+1;
}
cur++;
}
start=cur=0;
while (str[cur]) {
if (str[cur]==SPECIAL_CHAR || str[cur]==' ') {
reverse(str, start, cur-1);
start=cur+1;
}
cur++;
}
return;
}
void reverse(char *str, int beg, int end) {
while (beg < end) {
char temp = str[beg];
str[beg] = str[end];
str[end] = temp;
beg++; end--;
}
return;
}
i have a couple of test cases in mind but what does the question mean by "handle special chars"? can you give an example of special char?