EXAM1 Sample Questions
1. What is an API? Write an example API for buying gas using the GasPump class. What methods do you expose to achieve what goals? Show that you understand designing an API from the client side (the user) and the implementer side (the person who wrote the GasPump class).
2. What is the runtime of the following method reverseWords1 based on the input string size. Break it down into each type of compare, assignment, variable declaration, and array access. Describe the worst case input and the best case input.
This code does this: reverseWords1(“He is the one”) -> “one the is He”
private static void reverse(char[] buf, int start, int end) { for (int i = start, j = end - 1; i < j; i++, j--) { char swap = buf[i]; buf[i] = buf[j]; buf[j] = swap; } } public static String reverseWords1(String sentence) { char[] buf = sentence.toCharArray(); // Reverse the string, character-wise reverse(buf, 0, buf.length); // Within each word, reverse the characters again int wordEnd = 0; for (int wordStart = 0; wordStart < buf.length; wordStart = wordEnd + 1) { for (wordEnd = wordStart; wordEnd < buf.length && buf[wordEnd] != ' '; wordEnd++) {} // wordStart is at the start of a word. // wordEnd is just past the end of the word. reverse(buf, wordStart, wordEnd); } return new String(buf); }
Code source: http://codereview.stackexchange.com/questions/37364/reversing-words-in-a-string