Pregunta de entrevista

Entrevista de Technical Program Manager

-

Amazon

Given a string like "I'm being interviewed by Amazon" implement a method that reverses the given string so that it looks like "Amazon by interviewed being I'm".

Respuesta

Respuestas de entrevistas

10 respuestas

4

we can first reverse the whole string, and then reverse the individual words O(n) complexity

jack en

1

3-line solution in PowerShell: $str = "I'm being interviewed by Amazon".Split() $([array]::Reverse($str) ) [string]$str

Anónimo en

0

" ".join("I'm being interviewed by Amazon ".split()[::-1])

Jay en

0

String s="I'm being interviewed by Amazon "; String []arr=s.split(" "); String ans=""; for(int i=arr.length-1;i>=0;i--){ ans=ans+arr[i]+" "; } System.out.println(ans); }

Anónimo en

0

/** * Jun Zheng, Rice Univ * An interview question of Amazon * Java 7, Eclipse * Reverse a sentence, e.g., "Amazon is so gay" to "gay so is Amazon" * @param str * @return */ private String reverseSentence(String str){ str=new StringBuffer(str).reverse().toString(); int j=0; for(int i=0;i

Jun Zheng en

0

Private String ReverseStr(String reverseMe){ StringTokenizer st = new StringTokenizer(reverseMe); int count; String[] iamReversed = new String[j=st.countTokens()] while(st.hasMoreElements()){ } }

Karthik en

1

Pressed tab and enter and my comment got posted beofre even i could complete the code. here goes the complete method, Private String ReverseStr(String reverseMe){ StringTokenizer st = new StringTokenizer(reverseMe); int count; String[] iamReversed = new String[j=st.countTokens()] while(st.hasMoreElements()){ iamReversed[--j] = st.nextElement().toString()+" "; } return iamReversed; }

Karthik en

0

int main() { string s; cout << "Enter string: "; getline(cin,s); string newstr; int spaces = 0, pos, start = 0; for ( int i = 0; i < s.length(); i++) if (s[i] == ' ') spaces++; for ( int i = 0; i < spaces; i++) { pos = s.find(" ",start); newstr = (s.substr(start,(pos-start))) + " " + newstr; start = pos + 1; } newstr = (s.substr(start,(s.length()-start))) + " " + newstr; cout << newstr << endl; return 0; }

Abhishek en

1

One liner in Python: def reverse(str): return " ".join(str.split(" ")[::-1])

Phillip Ratliff en

1

In java: String str = "I'm being interviewed by Amazon"; String pieces[] = foo.split(); String reversedFoo; for (int i = pieces.length - 1; i >= 0; i--) { reversedFoo += pieces[i]; if (i > 0) reversedFoo += " "; } System.out.println(reversedFoo);

why not? en

Añadir respuestas o comentarios

Para publicar un comentario sobre esto, inicia sesión o regístrate.