Google Interview Question
1,225 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
package asaf;
public class ReverseWordsInString {
public static void main(String[] args) {
System.out.println(reverse(new StringBuffer("Reverse all the words in a string!")));
}
private static StringBuffer reverse(StringBuffer s) {
int fromIndex = 0;
int toIndex;
boolean reachTheEnd = false;
do {
toIndex = s.indexOf(" ", fromIndex);
if (toIndex == -1) {
reachTheEnd = true;
toIndex=s.length();
}
reverseWord(s, fromIndex, toIndex-1);
fromIndex = toIndex + 1;
} while (!reachTheEnd);
return s;
}
private static void reverseWord(StringBuffer s, int start, int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start++, s.charAt(end));
s.setCharAt(end--, temp);
}
}
}
// will print "esreveR lla eht sdrow ni a !gnirts"
Helpful Answer?
Yes |
No
Inappropriate?
public static void main( String[] args) {
//reverse all words in a string
String reverseString =null;
StringBuffer reverseWord = null;
String string = "my name is hello";
String[] newstring = string.split(" ");
int i, j;
int wordLength = 0;
StringBuffer sb = new StringBuffer();
for (i = 0; i<newstring.length; i++){
wordLength = newstring[i].length();
for (j = wordLength;j>0;j--){
char character= newstring[i].charAt(j-1);
reverseWord =sb.append(character);
}
reverseWord = reverseWord.append(" ");
reverseString = reverseWord.toString();
}
System.out.print(reverseString);
}
}
Helpful Answer?
Yes |
No
Inappropriate?
char[] toRevChar = toRev.toCharArray();
String res ="";
String word ="";
for (int i=0; i<toRevChar.length; ++i){
if (toRevChar[i] != ' '){
word = toRevChar[i] + word;
}
else {
res = res + word+ " ";
word="";
}
if (i == toRevChar.length-1){
res = res + word+ " ";
word="";
}
}
System.out.println(res);
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
0 of 0 people found this helpful
by Anonymous:
public class ReverseWordsInString {
public static void main(String[] args) {
System.out.println(reverse("Reverse all the words in a string"));
}
private static String reverse(String s) {
String result = "";
String space = "";
for (String word : s.split(" ")) {
result = word + space + result;
space = " ";
}
return result;
}
}