SignPost Interview Question
Software Engineer / DevelopersCountry: United States
def reverseReplace(original_string, search_string, replacement_string)
return nil if search_string.is_a?(String) && search_string.split.length > 1
original_string_as_array = original_string.split
original_string_as_array.each_with_index do |one_word, index|
original_string_as_array[index] = original_string_as_array[index].replace(replacement_string) if one_word == search_string.to_s
end
original_string_as_array.join(' ').split.reverse.join(' ')
end
def reverseReplace(str1, str2, str3):
return helper(str1.replace(str2,str3))
def helper(text):
t=""
for c in text:
if c==' ':
text=text.replace(t,"".join(reversed(t)))
t=""
else:
t+=c
text=text.replace(t,"".join(reversed(t)))
text="".join(reversed(text))
return text
print reverseReplace("I like cats", "cats", "dogs")
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include "reverse_replace.h"
struct Node {
int start_index;
int end_index;
Node * next;
};
void
push
( Node *& top, int start_index, int end_index )
{
Node * temp = (Node * ) calloc( 1, sizeof( Node ) );
temp->start_index = start_index;
temp->end_index = end_index;
temp->next = top;
top = temp;
}
void
print
( char const * arr, int start, int end)
{
for( int i = start; i < end; ++i){
std::cout << arr[i];
}
std::cout << std::endl;
}
Node *
createStack
( char const * string )
{
Node * top = nullptr;
int start = 0;
int i = 0;
for( ; string[i] != '\0'; ++i){
if( ' ' == string[i]){
push( top, start, i);
start = i + 1;
}
}
if( start != i){
push( top, start, i);
}
return top;
}
void
destroy_stack
( Node * top )
{
for( Node* curr = top; curr != nullptr; ){
Node * temp = curr;
curr = curr->next;
free( temp );
}
}
char * reverseReplace
( char const * string, char const * find, char const * replace, char * buffer )
{
int replace_length = strlen(replace);
Node * top = createStack( string );
int i = 0;
if( ' ' == string[top->end_index]){
buffer[i++] = ' ';
}
for( Node * curr = top; curr != nullptr; curr = curr->next){
if( std::equal( &string[curr->start_index], &string[curr->end_index], find)){
memcpy( buffer + i, replace, replace_length);
i += replace_length;
}
else {
int length = curr->end_index - curr->start_index;
memcpy( buffer + i, string + curr->start_index, length);
i += length;
}
buffer[i++] = ' ';
}
buffer[i - 1] = '\0';
destroy_stack( top );
return buffer;
}
// Java Code
// Usage Example:
// System.out.println(StringOp.wordReplace("Hello World cats", "cats", "dogs"));
public static String wordReplace(String str, String targeted, String replace)
{
int common_chars = 0;
String Result = "";
for(int i=0; i < str.length(); i++)
{
if(str.charAt(i) == targeted.charAt(common_chars))
{
common_chars++;
if(common_chars == targeted.length())
{
Result += replace;
common_chars = 0;
}
}
else
{
if(common_chars != 0)
{
for(int j=common_chars; j > 0; j--)
{
Result += str.charAt(i - j);
}
common_chars = 0;
}
Result += str.charAt(i);
}
}
return Result;
}
// Java Code
// Usage Example:
// System.out.println(StringOp.wordReplace("Hello World cats", "cats", "dogs"));
public static String wordReplace(String str, String targeted, String replace)
{
int common_chars = 0;
String Result = "";
for(int i=0; i < str.length(); i++)
{
if(str.charAt(i) == targeted.charAt(common_chars))
{
common_chars++;
if(common_chars == targeted.length())
{
Result += replace;
common_chars = 0;
}
}
else
{
if(common_chars != 0)
{
for(int j=common_chars; j > 0; j--)
{
Result += str.charAt(i - j);
}
common_chars = 0;
}
Result += str.charAt(i);
}
}
return Result;
}
//c coding
//code showing some runtime problem but the logic is correct, i am sure about logic.(99%)
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void reverse_replace(char [],char *,char *);
int main()
{
char arr[50],serch[10],replace[10];
puts("string : ");
gets(arr);
puts("search : ");
gets(serch);
puts("replace : ");
gets(replace);
reverse_replace(arr,serch,replace);
}
void reverse_replace(char arr[],char *s,char *r)
{
int i=1;
char *newn[20];
newn[0]=strtok(arr," ");
if(!strcmp(newn[0],s))
{
newn[0]=r;
}
if(!newn[0])
exit(0);
while(i<20)
{
newn[i]=strtok(NULL," ");
if(!strcmp(newn[i],s))
{
newn[i]=r;
}
if(!newn[i])
break;
}
while(i--<=0)
{
printf("%s ",newn[i]);
}
}
public class ReverseString {
public static void reverseReplace (String str, String targeted, String replace){
int numSpaces=0;
for(int i=0; i<str.length();i++){
if (str.charAt(i) == ' ')
numSpaces++;
}
String[] word=new String[numSpaces+1];
String[] wordReverse = new String[numSpaces+1];
//check the number of empty space in a string
int wordCount=0;
int startIndex=0;
for(int i=0; i<str.length();i++){
if (str.charAt(i) == ' ')
{
word[wordCount]=str.substring(startIndex, i);
wordCount++;
startIndex=i+1;
}
if(i==(str.length())-1)
word[wordCount]=str.substring(startIndex, (str.length()));
}
//replace the targeted word with the string replace
for(int i=0; i<word.length;i++)
{
if(word[i].equals("cats")){
word[i] = replace;
}
}
//convert string to an array of characters and back to string in reverse order
for(int i=0;i<word.length;i++)
wordReverse[i] = new String(convertStrtoChar(word[i]));
//display the final string
for(int i=0; i<word.length;i++)
{
System.out.print(word[i]+" ");
}
System.out.println(" ");
String strReverse="";
//display the final string in reverse order
for(int i=(wordReverse.length-1); i>=0; i--){
strReverse = strReverse + " "+ wordReverse[i];
}
System.out.println("Replace & Reverse words :" +strReverse);
}// end of reverseReplace
public static char[] convertStrtoChar(String str){
//convert string to an array of characters
char[] chArray = str.toCharArray();
int len = chArray.length;
int count=0;
char[] chArray1 = new char[len];
for(int i=(len-1); i>=0;i--){
chArray1[count]=chArray[i];
count++;
}
return chArray1;
}
public static void main(String[] args) {
String originalStr = "Harry like cats";
System.out.println("Original Sentence :"+ originalStr);
System.out.print("Replace Word :");
reverseReplace(originalStr, "cats", "dogs");
String originalStr1 = "Harry Potter Nubee like cats";
System.out.println("Original Sentence :"+ originalStr);
System.out.print("Replace Word :");
reverseReplace(originalStr1, "cats", "dogs");
}
}
I have improved the solution.....
You can enter any string...of any length....(20 is boundry)....
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[20][20],b[20],c[20],ch;
static int i,j,k;
printf("Enter the string:\n");
ch=getchar();
do
{
if(ch==' ')
{
a[i][j]='\0';
i++;
j=0;
}
else if(ch=='\n')
{
a[i][j]='\0';
}
else
{
a[i][j++]=ch;
}
} while((ch=getchar())!='\n');
printf("Enter the string to be replaced:");
gets(b);
printf("\nEnter the string by which replacement is to be done:");
gets(c);
for(k=0;k<=i;k++)
{
if(strcmp(a[k],b)==0)
{
strcpy(a[k],c);
}
}
for(k=i;k>=0;k--)
{
fputs(a[k],stdout);
printf(" ");
}
getch();
}
package org.test.string;
public class StringReplace {
public static String reverseReplace(String orig,String match,String replace){
String split[] = orig.split(" ");
StringBuilder builder = new StringBuilder();
String matchStr = split[split.length-1];
if(matchStr.equals(match)){
split[split.length-1] = replace;
}
for (int i = split.length -1; i >= 0; i--) {
builder.append(split[i]).append(" " );
}
return builder.toString().trim();
}
public static void main(String[] args) {
System.out.println(reverseReplace("I like cats", "cats", "dogs"));
System.out.println(reverseReplace("I like cats", "dogs", "dogs"));
}
}
function reverseReplace(phrase, search, replacement)
{
phrase = phrase.replace(search, replacement);
var newPhrase = phrase.split(" ").reverse();
var reversePhrase = "";
newPhrase.forEach (function(word){
reversePhrase += word+" ";
});
alert(reversePhrase);
}
reverseReplace("I like cats", "mice", "dogs");
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void reverse(string str1,string str2,string str3){
vector<string> final;
stringstream in(str1);
string temp;
while(in>>temp){
if(temp==str2)
temp=str3;
final.push_back(temp);
}
for(int i=final.size()-1;i>=0;i--)
cout<<final.at(i)<<"\n";
}
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void reverse(string str1,string str2,string str3){
vector<string> final;
stringstream in(str1);
string temp;
while(in>>temp){
if(temp==str2)
temp=str3;
final.push_back(temp);
}
for(int i=final.size()-1;i>=0;i--)
cout<<final.at(i)<<"\n";
}
def reverseReplace(text,word,replaceWord):
toPrint = ""
textArr = text.split(" ")
for idx in range(len(textArr),0,-1):
if(idx != 0):
if(textArr[idx-1] == word):
toPrint = toPrint + " " + replaceWord
else:
toPrint = toPrint + " "+ textArr[idx-1]
print(toPrint)
def main():
reverseReplace("I like cats", "cats", "dogs")
main()
- rockuw September 19, 2012