3
\$\begingroup\$

An algorithm to reverse characters of each word in a sentence. What would be your concerns regarding the following solution?

Example input: "I love New York" output: "I evol weN kroY"

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        final String words = bufferedReader.readLine().trim();
        final char[] reversedWord = reverseWords(words.toCharArray());

        bufferedWriter.write(reversedWord);

        bufferedReader.close();
        bufferedWriter.close();
    }

    private static char[] reverseWords(char[] input) {
        int startIndex = 0;
        int endIndex = 0;
        while (endIndex < input.length) {
            final boolean isLastWord = endIndex == input.length - 1;
            if (input[endIndex] == ' ' || isLastWord) {
                if (isLastWord) {
                    endIndex++;
                }
                reverseWord(input, startIndex, endIndex);
                startIndex = ++endIndex;
            } else {
                endIndex++;
            }
        }
        return input;
    }

    private static void reverseWord(char[] word, int startIndex, int endIndexExclusive) {
        final int wordLength = (endIndexExclusive - startIndex);
        for (int i = 0; i < wordLength/2; i++) {
            final char temp = word[startIndex + i];
            word[startIndex + i] = word[endIndexExclusive - i - 1];
            word[endIndexExclusive - i - 1] = temp;
        }
    }
}

Unit tests would be like:

public class QuestionOneTest {
    @Test
    public static should_reverse_chars() {
        // given
        final String input = "I love New York";

        // when
        final char[] reversed = QuestionOne.reverseWords(input.toCharArray());

        // then
        assert String.copyValueOf(reversed).equals("I evol weN kroY");
    }
}
\$\endgroup\$
  • \$\begingroup\$ Could you include some unit tests to verify the results of the algorithm? \$\endgroup\$ – dfhwze Aug 16 at 7:35
2
\$\begingroup\$

main()

  1. it is considered bad practice for the main() method. at the very least, it is customary to catch all exceptions and print the stack trace to allow debugging.

  2. All IO resources (files, network sockets, DB connetions, etc) should be closed before the program exits. Java 7 has introduced the try-with-resources Statement where the compiler ensures proper closure of resources in all control flows (including exceptions)

reverseWords()

I do not see any branch where endIndex is not advanced. so why is this performed separately for each branch? it can, and should, be done in one place.

Unit tests

the unit tests are missing cases of null input, empty string input, string with one word, string with multiple spaces between words: "multi space between words", string with tab character instead of space between words.

\$\endgroup\$
2
\$\begingroup\$

If you don't want to reinvent the wheel, you can implement a very short and simple solution using java.util:

public class Main {
    public static void main(final String[] args) throws IOException {
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        final String line = bufferedReader.readLine().trim();
        List<String> words = Arrays.asList(line.split("\\s+"));

        String reversedWords = reverseWords(words);

        bufferedWriter.write(reversedWords.toCharArray());

        bufferedReader.close();
        bufferedWriter.close();
    }

    private static String reverseWords(final List<String> words) {
        return words.stream().map(word -> reverseWord(word)).collect(Collectors.joining(" "));
    }

    private static String reverseWord(final String word) {
        return new StringBuilder(word).reverse().toString();
    }
}
\$\endgroup\$
  • \$\begingroup\$ that is not code review \$\endgroup\$ – Sharon Ben Asher Aug 18 at 12:50
  • 3
    \$\begingroup\$ Sure it is. “Don’t invent square wheels” is always a valid code review. \$\endgroup\$ – RubberDuck Aug 18 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.