Saturday, January 30, 2016

Reverse order of words in a sentence

Question: Given an input string, reverse all the words. To clarify, input: “Interviews are awesome!” output: “awesome! are Interviews”. Consider all consecutive non-whitespace characters as individual words. If there are multiple spaces between words reduce them to a single white space. Also remove all leading and trailing whitespaces. So, the output for ” CS degree”, “CS degree”, “CS degree “, or ” CS degree ” are all the same: “degree CS”.
Algo:
1.  Reverse the entire sentence
2.  Reverse each word in a sentence
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
     * Reverse the order of words in a sentence
     * @param str
     */
    String reverseOrderOfWords(String str)
    {
        // Reverse entire sentence
        String reverseStr = reverse(str);
         
        // Reverse each word in the sentence
        String[] reverseWords = reverseStr.split(" ");
        StringBuilder reverseSb = new StringBuilder();
        for(String word:reverseWords){
            reverseSb.append(reverse(word)).append(" ");
        }
        return reverseSb.toString();
    }
     
    /**
     * Reverse the string which is between start index to end index
     *
     * @param str
     * @param startIndex
     * @param endIndex
     */
    String reverse(String str)
    {
        char[] charArray = str.toCharArray();
        for(int i=0,j=charArray.length-1; i<j; i++,j--) {
            char temp=charArray[i];
            charArray[i]= charArray[j];
            charArray[j]= temp;
        }
        return String.valueOf(charArray);
    }

No comments:

Post a Comment