Salesforce Interview Question
InternsTeam: Quality Engineer Intern
Country: United States
This will leave a space at the end of the reversed string. We can solve it by either trimming it at the end.
String word = " i am bad . ";
char[] a = word.toCharArray();
StringBuffer sb = new StringBuffer();
int i = a.length - 1;
int j = a.length - 1;
int temp;
System.out.print("'");
while(i>=0)
{
if(a[i] != ' ') {
i--;
}
else{
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print(a[i]);
i--;
j=i;
}
}
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print("'");
}
Without the built-in split function, I would solve it recursively:
import java.util.ArrayList;
public class StringReverse {
String str = "";
public StringReverse(String str) {
this.str = str;
}
//first reverse the string and save in an arraylist.
//use the string builder to append them altogether.
public String reverse(){
ArrayList<String> res = reverseAndSplit(this.str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < res.size(); i++) {
sb.append(res.get(i) + " ");
}
return sb.toString();
}
//Find the first space and save the word before that in beforeSpace.
//Reverse the string after the first space recursively.
//append beforeSpace to the end of array.
public ArrayList<String> reverseAndSplit(String str) {
str = str.trim();
if (str.indexOf(' ') == -1) {
ArrayList<String> res = new ArrayList<String>();
res.add(str);
return res;
} else {
String beforeSpace = str.substring(0, str.indexOf(' '));
ArrayList<String> res = reverseAndSplit(str.substring(str
.indexOf(' ') + 1));
res.add(beforeSpace);
return res;
}
}
public static void main(String[] args) {
StringReverse sr = new StringReverse("I am in the river");
String str = sr.reverse();
System.out.println(str);
}
}
First, I reverse the whole string: "I am bad" -> "dab ma I"
Then I reverse each word: "dab ma I" -> "bad am I"
Code may look like this:
// reverse word order in a sentence:
// "I am bad" -> "bad am I"
// NNN
#include <iostream>
#include <string>
using namespace std;
string reverseStr(string S, int u, int v){
for(int i = 0; i<(v-u+1)/2;i++){
swap(S[u+i],S[v-i]);
};
return S;
};
string reverseSentence(string S){
int st=0, ed=0;
int len = S.length();
S = reverseStr(S,0,len-1);
while(st<len-1){
while((st<len) and (S[st] == ' ')) st++;
ed = st;
while((ed<len) and (S[ed] != ' ')) ed++;
ed--;
//cout <<st<<" "<<ed<<endl;
S = reverseStr(S,st,ed);
//cout <<S<<endl;
st = ed+1;
};
return S;
};
int main()
{
string sentence = " This is a sentence with multiple spaces . 1 22 333 4444 ";
string reversed = reverseSentence(sentence);
cout <<"Original sentence:["<<sentence<<"]\n";
cout <<"Reversed sentence:["<<reversed<<"]\n";
return 0;
}
What about if we use stack (LIFO).
import java.util.Stack;
public class WordsReversed {
private String reverse(String str) {
Stack<String> stack = new Stack<String>();
String temp = "";
while(true) {
if(str.indexOf(' ') > 0) {
temp = str.substring(0, str.indexOf(' '));
str = str.substring(temp.length()+1, str.length());
stack.push(temp.trim());
}
else {
stack.push(str.trim());
break;
}
}
str = "";
while(!stack.empty())
{
str = str + stack.pop() + " ";
}
return str;
}
public static void main(String[] args) {
WordsReversed wr = new WordsReversed();
String string = "I love programming";
System.out.println(wr.reverse(string));
}
}
public static String reverseWords(String s)
{
String[] sa = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i=sa.length-1; i>=0; i--)
{
sb.append(sa[i]);
}
int counter = 0;
for(int i=s.length()-1;i>=0; i--)
{
if(s.charAt(i) == ' ')
{
sb.insert(counter, " ");
}
counter++;
}
return sb.toString();
}
#include<iostream>
#include<stack>
using namespace std;
int main()
{
char gg[] = "i am good test it";
char *ptr = NULL;
stack<string> stac;
ptr = strtok(gg," ");
while(NULL != ptr)
{
stac.push(ptr);
//cout<<" "<<ptr<<endl;
ptr = strtok(NULL," ");
}
while(!stac.empty())
{
cout<<stac.top()<<endl;
stac.pop();
}
getchar();
}
#include <iostream>
#include<stdio.h>
//To reverse the words of a string using stack
using namespace std;
void rev(char t[],int k)//used to reverse the string stored in stack
{
for(int i=k-1;i>=0;--i)
cout<<t[i];
cout<<" ";
}
void reverse(char a[])
{
char stack[200],t[40];
int top=-1,k;
for(int i=0;a[i]!='\0';++i)//used to store the string in stack
stack[++top]=a[i];
for(int i=top;i>=0;)//used to find the substring till we find space as delimiter
{
k=0;
for(int j=i;j>=0;--j)
{
if(stack[j]==' ')
break;
else
t[k++]=stack[j];
}
rev(t,k);
i=i-(k+1);
}
}
int main()
{
char ch;
char a[100];
cout<<"\nEnter the string:";
gets(a);
cout<<"\nReverse sentence:";
reverse(a);
cin>>ch;
return 0;
}
#include<stdio.h>
#include<string.h>
int main()
{
printf("enter a string\n");
char *str;
str=(char*)malloc(50*sizeof(char));
fgets(str,50,stdin);
int ii=0,i=0;
char *arr=(char*)malloc(10*sizeof(char));
int j=0;
int k;
while(str[ii++]!='\n');
for(i=ii-2;i>=0;i--)
{
if(str[i]!=' ' )
{
arr[j++]=str[i];
}
else
{
for(k=j-1;k>=0;k--)
{
printf("%c",arr[k]);
}
printf(" ");
j=0;
}
if (i==0)
{
for(k=j-1;k>=0;k--)
{
printf("%c",arr[k]);
}
}
}
system("pause");
return 0;
}
void reverse(char *str)
{
char *temp ;
temp = (char*)malloc(sizeof(char)*strlen(str));
if(str==NULL)
return;
int len= strlen(str);
if(len==0 || len==1)
return;
int i=0;
int j=0;
int c=0;
for(j=len-1; j>0; j--)
{
if(*(str+j)==' ')
{
for(c=j+1;c<len;c++,i++)
{
*(temp+i)=*(str+c);
if(*(str+c)==' ')
break;
//i++;
}
*(temp+i)=' '; i++;
}
}
for(c=0;(*(str+c)!=' ');c++,i++)
{
*(temp+i)=*(str+c);
}
*(temp+i)='\0';
printf("%s",temp);
}
public class ReverseSentance {
public String reverseMe(String reverseme) {
String sentance = reverseme;
String[] words = sentance.split(" ");
String tmp = "";
for (int i = words.length - 1; i >= 0; i--) {
tmp = tmp + " " + words[i];
}
return tmp.trim();
}
public static void main(String[] args) {
ReverseSentance rev = new ReverseSentance();
System.out.println(rev.reverseMe("I am good"));
}
}
public String getReversedStringWithoutSplit(String inputs, Boolean reverseWord){
String singleString = "";
String result = "";
for(int i= inputs.toCharArray().length -1; i>=0; i--) {
singleString += inputs.toCharArray()[i];
if(inputs.toCharArray()[i] == (char)32 && reverseWord){
result += getReversedStringWithoutSplit(singleString.trim(), false) + " ";
singleString = "";
}
}
return reverseWord ? result += getReversedStringWithoutSplit(singleString, false):singleString;
}
public String getReversedStringWithoutSplit(String inputs, Boolean reverseWord){
String singleString = "";
String result = "";
for(int i= inputs.toCharArray().length -1; i>=0; i--) {
singleString += inputs.toCharArray()[i];
if(inputs.toCharArray()[i] == (char)32 && reverseWord){
result += getReversedStringWithoutSplit(singleString.trim(), false) + " ";
singleString = "";
}
}
return reverseWord ? result += getReversedStringWithoutSplit(singleString, false):singleString;
}
If spaces can be considered to mark end and start for words --
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("reverse of i am will - " + reverseWords("i am will"));
}
public static String reverseWords(String str){
String newString = "";
String arr[] = str.split(" ");
for(int i = arr.length-1; i >= 0; i--){
newString = newString + " " + arr[i];
}
return newString;
}
}
private reverseString(){
String word = " i am bad . ";
char[] a = word.toCharArray();
StringBuffer sb = new StringBuffer();
int i = a.length - 1;
int j = a.length - 1;
int temp;
System.out.print("'");
while(i>=0)
{
if(a[i] != ' ') {
i--;
}
else{
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print(a[i]);
i--;
j=i;
}
}
temp = i+1;
while(temp <= j){
System.out.print(a[temp]);
temp++;
}
System.out.print("'");
}
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
public static String reverse_word(String s) {
StringTokenizer st = new StringTokenizer(s);
Stack<String> sk = new Stack<String>();
while (st.hasMoreTokens()) {
sk.push(st.nextToken());
}
String rs = "";
while (!sk.isEmpty()) {
rs += sk.pop() + " ";
}
return rs.trim();
}
public static void main(String[] args) {
String s = "I am no good";
System.out.println("Before: " + s);
System.out.println(" After: " + reverse_word(s));
}
/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}
}
C# Solution
public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append($"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}
public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append($"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}
public static string ReverseWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
var length = input.Length - 1;
var returnValue = new StringBuilder();
var lastIndex = length;
while (length >= 0)
{
if (input[length] == ' ')
{
var word = input.Substring(length + 1, (lastIndex - length));
returnValue = returnValue.Append($"{word} ");
lastIndex = length;
}
if (length == 0)
{
var word = input.Substring(length, (lastIndex - length));
returnValue = returnValue.Append(word);
lastIndex = length;
}
length--;
}
return returnValue.ToString();
}
C# Solution
public static string ReverseByWord(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
var charIndex = input.Length - 1;
var returnValue = new StringBuilder();
var currentWord = string.Empty;
while (charIndex >= 0)
{
if (input[charIndex] != ' ')
{
currentWord = currentWord + input[charIndex];
}
if (input[charIndex] == ' ' || charIndex == 0)
{
//complete the word in reverse string.
var counter = currentWord.Length - 1;
while (counter >= 0)
{
returnValue.Append(currentWord[counter]);
counter--;
}
currentWord = "";
if (charIndex != 0)
{
returnValue.Append(" ");
}
}
charIndex--;
}
return returnValue.ToString();
}
package questions;
import java.lang.Exception;
public class Sf_Practice {
public static void main(String[] args) {
// Testcases
String []arr = {""," ","a", "aabb", "132!!@@@##!!", "aswbsdwwAQQQ", " hello how are you !! :) "};
for (int i = 0; i < arr.length; i++) {
try {
String res = reverseStrings(arr[i]);
System.out.println(res);
} catch (Exception e) {
if (e.getMessage().equals("Empty String !!!") ) {
System.out.print("Exception caught :)\n");
} else {
e.printStackTrace();
}
}
}
}
// reverse Strings method.
public static String reverseStrings(String s) throws Exception {
if (s.isEmpty()) {
throw new Exception("Empty String !!!");
}
if (s.length() <= 1) {
return s;
} else {
String reverse = "";
int cnt = s.length();
do {
cnt--;
String tmp = Character.toString(s.charAt(cnt));
reverse = reverse + tmp;
} while (cnt != 0);
return reverse;
}
}
}
- mahdi.oraei February 26, 2014