Interview Question

Interview Redmond, WA

Write a function (in your preferred language C, C++, or

  Java) that will take the given string and return the reverse. (ie. input:"abc def ghi" output:"ihg fed cba") Optimize the above code (if possible). Now knowing that the original function you wrote in pt1 is being used by other programs and cannot be modified write another function that when called will utilize the function from pt1 to only reverse the words in the sentence. (ie. input:"abc def ghi" output:"ghi def abc") Test your code.
Answer

Interview Answer

2 Answers

0

public class TestRun2 { public static void main(String[] args) { String inputString = "abc def ghi"; System.out.println(reverseString(inputString)); // now reverse the words System.out.println(reverseWords(inputString)); } public static String reverseString(String input) { char[] inputCharArray = input.toCharArray(); char[] returnCharArray = new char[inputCharArray.length]; for(int i=0; i<inputCharArray.length; i++) { returnCharArray[i] = inputCharArray[inputCharArray.length - 1 - i]; } return new String(returnCharArray); } public static String reverseWords(String input) { // Firstly, for the given string, reverse all the words one by one but maintain order String[] splitStrings = input.split(" "); String reversedWords = ""; for (int i=0; i<splitStrings.length; i++) { reversedWords += reverseString(splitStrings[i]) + " "; } // remove trailing space reversedWords = reversedWords.trim(); // now reverse full string return reverseString(reversedWords); } } JUnit 4 class: import static org.junit.Assert.*; import org.junit.Test; public class TestRun2Test { @Test public void testReverseString() { String inputString = "abc def ghi"; assertEquals(TestRun2.reverseString(inputString),"ihg fed cba"); } @Test public void testReverseWords() { String inputString = "abc def ghi"; assertEquals(TestRun2.reverseWords(inputString),"ghi def abc"); } }

Benny on Dec 17, 2012
0

string reverseString(string str) { int i = 0; while(i < str.size()/2) { char temp = str[i]; str[i] = str[str.size() - i - 1]; str[str.size() - i - 1] = temp; ++i; } return str; } int main(int argc, char *argv[]) { string temp = "abc def ghi"; cout << temp << endl; cout << reverseString(temp) << endl; } To do the second part, give the algorithm each word, and concatenate them.

Anonymous on Jan 7, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.