Pergunta de entrevista da empresa Google

Reverse all the words in a string

Respostas da entrevista

Sigiloso

1 de dez. de 2011

package asaf; 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; } }

Sigiloso

1 de dez. de 2011

package asaf; 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; } }

Sigiloso

1 de dez. de 2011

This is another version that will reverse each word in place 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"

Sigiloso

13 de jan. de 2012

public class hello { 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; i0;j--){ char character= newstring[i].charAt(j-1); reverseWord =sb.append(character); } reverseWord = reverseWord.append(" "); reverseString = reverseWord.toString(); } System.out.print(reverseString); } }

Sigiloso

15 de jan. de 2012

String toRev = "I am very nice"; char[] toRevChar = toRev.toCharArray(); String res =""; String word =""; for (int i=0; i