Microsoft Interview Question
Software Engineer in TestsTeam: Server and tools in microsoft erp
Country: United States
Interview Type: In-Person
void subreverse(char *str, int begin, int end)
{
end--;
while ( begin < end )
{
swap(str[begin++], str[end--]);
}
}
char* reversestr(char *str)
{
int len = strlen(str);
int begin = 0;
int end = 0;
for ( int i=0; i<len; )
{
while( i!=0 && str[i] != '\0' && str[i] != ' ')
i++;
if ( str[i] == '\0' )
break;
else if ( i== 0)
begin = i;
else
begin = i+1;
i++;
while ( str[i] != '\0' && str[i] != ' ')
i++;
end = i;
subreverse(str, begin, end);
}
return str;
}
public class test {
private void reverseWords(StringBuffer sentence, int length) {
for(int j=0, i=0; i < length ; i++) {
if(sentence.charAt(i) == ' ' || i + 1 == length) {
if(i + 1 == length) {
sentence = reverseWord(sentence,j,i);
} else {
sentence = reverseWord(sentence,j,i-1);
}
j = i + 1;
}
}
System.out.println(sentence);
}
private StringBuffer reverseWord(StringBuffer sentence, int start, int end) {
while(start < end) {
char temp = sentence.charAt(start);
sentence.setCharAt(start, sentence.charAt(end));
sentence.setCharAt(end, temp);
start++;
end--;
}
return sentence;
}
public static void main(String args[]) {
test t = new test();
StringBuffer sb = new StringBuffer("hello world");
t.reverseWords(sb, sb.length());
}
}
/* Author - JITENDRA SINGH
CDAC HYDERABAD
*/
void rev(char *l,char *r)
{
int i=0,t;
while(l<r)
{
t = *l;
*l = *r;
*r = t;
l++;
r--;
}
}
void main()
{
char *x,*y,*S1,str[150];
printf("\n Enter String\n");
fgets(1,str ,150);
printf("\ngiven = %s",str);
for(S1 =str ; *S1 ;S1++);
x = str;
y = str;
while(x++ < S1)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
printf("\n\nconverted=%s",str);
}
Better solution:-
1) Split the string taking "space" as delimiter.
2)now just reverse the array of String using reverse() of StringBuffer.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// this program reverse string as follows : hello string --> olleh gnirts
void reverse(char[], int, int);
int main()
{
int l;
printf("enter the length of string\n");
scanf("%d", &l) ;
getchar();
char *str = malloc(sizeof(char) * l);
printf("enter the string\n");
gets( str);
int first = 0,i,last;
int len = strlen(str);
for(i=0; i<len; i++)
{
if(str[i] == ' ')
{
last = i-1;
reverse(str,first,last);
first = i+1;
}
if(i == len-1)
{
last = len-1;
reverse(str,first,last);
}
}
printf("%s\n", str);
}
void reverse(char str[], int first, int last)
{
int i,j;
char temp;
for(i=first,j=last; i<j; i++,j--)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
// its complexity is O(n*n) ..can anybody suggest some better algorithm?
typedef struct _node
{
char c;
struct _node *next;
}node;
main()
{
char *string = "Hello World This is a Sample Program";
node *word = NULL;
while(*string)
{
if(*string != ' ')
{
word = push(word, *string);
string++;
continue;
}
print(word);
printf(" ");
freenode(word);
word = NULL;
string++;
}
printf(" ");
print(word);
}
node* push(node *prev, char chr)
{
node *link = NULL;
link = (node *) malloc(sizeof(node));
link->c = chr;
link->next = prev;
return link;
}
void print(node *word)
{
if(word == NULL)
return;
printf("%c", word->c);
print(word->next);
}
void freenode(node *fnode)
{
if(fnode->next != NULL)
freenode(fnode->next);
free(fnode);
}
void reverseWordByWord(char c[])
{
int l = strlen(c);
char *temp = &c[0];
char *start_pos = NULL;
stack<char> s;
while (*temp != '\0')
{
if (*temp != ' ') {
if (start_pos == NULL) {
start_pos = temp;
}
s.push(*temp);
} else {
while (s.size() > 0) {
*start_pos = s.top();
s.pop();
start_pos++;
}
start_pos = NULL;
}
temp++;
}
if (s.size() > 0) {
while (s.size() > 0) {
*start_pos = s.top();
s.pop();
start_pos++;
}
}
}
#include<stdio.h>
int main()
{
char a[]="i am good";
char *p,*q,*r;
int c=0;
p=a;
while(*p!='\0')
{
p++;
}
p--;
while(c<strlen(a))
{
*q =*p;
q++;
p--;
c++;
}
c=0;
*q='\0';
while(c<strlen(a))
{
q--;
c++;
}
printf("%s",q);
getchar();
}
The above is the code for reversing the string or even a sentence which is a collection of words. Now if we want the words in the string to be reversed take an array of pointer like
char *a[]="i am solid";
now a[0] contains address of 'i" a[1] contains address of "am" a[2] contains address of "solid" now pass each and every value of a ie; a[0] a[1] a[2] to the above program assuming the above program as a function. Now your char *a[] contains "I ma dilos"
i have a simple solution to this problem.
we will traverse the string and push the charachters in a stack, until we get a space.
when space is encountered, empty the stack in a queue, and continue traversing the string.
finally the answer will be available in the queue.
Stack will reverse the individual words while queue will maintain there order.
please reply if you have any say on this.
Thanks
Ankit
public static void ReverseWordOfString(string s)
{
if (string.IsNullOrEmpty(s))
{
Console.WriteLine("String is empty");
return;
}
Stack<char> charStack = new Stack<char>();
var charArray = s.ToCharArray();
int length = charArray.Length;
Queue<char> result = new Queue<char>();
Console.WriteLine("input string : {0}", s);
for (int i = 0; i < length; i++)
{
if (charArray[i] != ' ')
{
charStack.Push(charArray[i]);
}
else
{
while (charStack.Count > 0)
{
result.Enqueue(charStack.Pop());
}
result.Enqueue(' ');
}
}
while (charStack.Count > 0)
{
result.Enqueue(charStack.Pop());
}
Console.Write("String After reversing the words : "); Console.Write(result.ToArray());
Console.WriteLine();
}
Following function can be used
void reverseWordByWord(char string[]) {
int len = strlen(string);
char *start = &string[0];
char *end = NULL;
for (int i=0;i<len;++i) {
if (string[i] == ' ') {
end = &string[i-1];
reverse(start, end);
start = i+1<len?&string[i+1]:NULL;
}
}
//reverse the last word
end = &string[len-1];
reverse(start, end);
}
RegEx can be used to split words.
public static string ReverseWordsInAString(string inputString)
{
StringBuilder sb = new StringBuilder();
//split the word with Regx
Regex regex = new Regex(@"\b+\w+|[\s.',:?]*\b");
MatchCollection matches = regex.Matches(inputString);
if (matches.Count > 0)
{
foreach (Match m in matches)
{
sb.Append(RevereseString(m.Value));
}
}
return sb.ToString();
}
private static string RevereseString(string s)
{
//Check for Null/Empty string
if (!string.IsNullOrWhiteSpace(s))
{
char[] newS = s.ToCharArray();
Array.Reverse(newS);
return new string(newS);
}
return s;
}
c++ code
#include<iostream>
#include<string>
using namespace std;
void ReverseLetters(std::string& s)
{
int i = 0;
int start = 0;
int l = s.length();
while (i < l)
{
if (s[i+1] == ' ')
{
int end = i;
while(start < end){
char c = s[start];
s[start++] = s[end];
s[end--] = c; }
i++;
while(s[i] == ' ' and i < l)
{
i++;
}
start = i;
}
i++;
}
}
private String ReverseWords(String s, String separators = " /t.,?!")
{
// ensure that the string has enough characters to reverse
if (s.Length <= 1) { return s; }
// check each character
StringBuilder ret = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (separators.Contains(s[i]))
{
ret.Append(s[i]);
continue;
}
// search for the rest of the word
Stack<char> wordReverser = new Stack<char>();
while (i < s.Length)
{
if (separators.Contains(s[i]))
{
i--; // backup i to be correct in the "for" loop
break;
}
wordReverser.Push(s[i]);
i++;
}
// empty word in reverse
while (wordReverser.Count > 0)
{
ret.Append(wordReverser.Pop());
}
}
return ret.ToString();
}
#include<iostream>
- anjalpetty April 20, 2012#include<string>
using namespace std;
void reverse(string& str, int st, int end) {
if (st > end) return;
char c;
int i,j;
for (i=st, j=0; i<(st+end)/2; ++i, ++j) {
c = str[i];
str[i] = str[end-j];
str[end-j] = c;
}
return;
}
int main() {
string str = "hello world";
cout << "before : " << str << endl;
int p = str.find(' ');
int len = str.length();
reverse(str, 0, p-1);
reverse(str, p+1, len-1);
cout << "after : " << str << endl;
}