Tuesday, June 30, 2015

Reverse Words in a String


Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Have you met this question in a real interview? 
Yes
Example

Clarification
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
public class Solution {
    /**
     * @param s : A string
     * @return : A string
     */
    public String reverseWords(String s) {
        // write your code
        char[] arr = s.trim().toCharArray();
        reverse(arr, 0, arr.length-1);
        for(int i = 0, j = 0; j <= arr.length; j++){
            if(j == arr.length || arr[j] == ' '){
                reverse(arr, i, j-1);
                i = j+1;
            }  
        }
        return new String(arr);
    }
   
    private void reverse(char[] s, int left, int right){
        while(left < right){
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}

No comments:

Post a Comment