LeetCode – Reverse Words in a String II (Java)

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Java Solution

public void reverseWords(char[] s) {
    int i=0;
    for(int j=0; j<s.length; j++){
        if(s[j]==' '){
            reverse(s, i, j-1);        
            i=j+1;
        }
    }
 
    reverse(s, i, s.length-1);
 
    reverse(s, 0, s.length-1);
}
 
public void reverse(char[] s, int i, int j){
    while(i<j){
        char temp = s[i];
        s[i]=s[j];
        s[j]=temp;
        i++;
        j--;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • karthik339

    I liked this implementaion. Fast and efficinent.

  • Huy

    I think from the moment you have array = string.split(” “); you are already using O(n) space, where n is the number of ‘ ‘ in the string.

  • Dnyanada Pramod Arjunwadkar


    String s="the sky is blue";
    String[] s1=s.split("\s");

    List l1=new ArrayList();
    l1=Arrays.asList(s1);
    Collections.reverse(l1);
    System.out.println("this-:"+l1);
    StringBuilder sb= new StringBuilder();
    for(int y=0;y<l1.size();y++)
    {
    if(y==l1.size()-1)
    {
    sb.append(l1.get(y));
    }
    else
    {
    sb.append(l1.get(y)+" ");
    }
    }
    String hy=sb.toString();
    hy.trim();
    System.out.print(hy);

  • sewa

    i think using a stringbuilder or stringbuffer would be better as they expand and contract as opposed to Strings that are immutable. this way, you dont keep allocating new spaces for every new append you do.

  • bpgen

    String s = “the sky is blue”;
    String[] splitted = s.split(” “);
    System.out.println(Arrays.stream(splitted).reduce(“”,(a,b)->b+” “+a));

  • Avinash Ujjwal

    I have written this code and tried to keep it simple. I think I have considered space and time complexity as well at same time. What’s your input about it, please let me know.

    public static String stringReverse(String string) {
    if(string == null) {
    return “”;
    }

    StringBuilder stringBuilder = new StringBuilder(“”);

    for(int i = string.length() – 1; i >= 0; i–) {
    if(Character.isWhitespace(string.charAt(i))) {
    stringBuilder.append(string.substring(i + 1, string.length() – stringBuilder.length())).append(” “);;
    }
    }

    stringBuilder.append(string.substring(0, string.length() – stringBuilder.length()));
    return stringBuilder.toString();
    }

  • Satyendra Talatam

    public void reverseString() {
    String original = “Please reverse me hello world”;
    int staticPointer = original.length() – 1;
    for (int movingPointer = original.length() – 1; movingPointer >= 0; movingPointer–) {
    if (original.charAt(movingPointer) == ‘ ‘) {
    int movingPointerTemp = movingPointer + 1;
    while (movingPointerTemp <= staticPointer) {
    System.out.print(original.charAt(movingPointerTemp));
    movingPointerTemp = movingPointerTemp + 1;
    }
    staticPointer = movingPointer – 1;
    System.out.print(" ");
    }
    }

    for (int i = 0; i < staticPointer; i++) {
    System.out.print(original.charAt(i));
    }
    }

  • NightCoder

    private static String reverse(String string) {
    // TODO Auto-generated method stub

    String[] array = string.split(” “);
    int start = 0;
    int end = array.length – 1;

    while(start < end){
    String temp = array[start];
    array[start] = array[end];
    array[end] = temp;
    start++;
    end–;
    }

    String str1 = Arrays.toString(array);
    return str1.substring(1,str1.length() – 1).replace(",", "");
    }

  • Noe Alejandro Perez Domínguez

    Possible one liner in Scala


    def reverseWords(s: String): String = s.split(' ').reverse.mkString(" ")

  • This works.

  • omar farag

    I have written this code, and I wonder if using the (“out” String) means allocating extra space?


    public static String StringRev(String s)
    {
    String out="";
    if(s==null)
    return "";

    for(int i=s.length()-1;i>0;i--)
    {
    if(Character.isWhitespace(s.charAt(i)))
    {
    s+=s.substring(i+1)+" ";
    s= s.substring(0, i);
    }
    }
    out+= s;
    return out;
    }

  • Christian

    How about this…

    public static String reverseWordsInString(String str){
    String[] arr = str.split(” “);
    String newArr = “”;
    for(int index = arr.length – 1; index >= 0; –index)
    newArr += ” ” + arr[index];
    return newArr.substring(1);
    }

    …where I used the ‘substring’ method to produce an output without space. I’m very new to Java and relatively new to programming so I don’t know how Java’s ‘behind-the-scenes’ work, thus I don’t know if my code is more efficient.

  • Raghu Mahajan

    cant use extra space

  • Raghu Mahajan

    we cant use any extra space

  • He means the input string is not always “The sky is blue”. It may be longer than 4 words. In that case, the 4 line code solution by stefan fails.

  • Samir Vasani

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s=”my name is ab be fh”,temp;
    String[] sDel=s.split(” “);
    int j= sDel.length-1;
    for(int i=0 ; i<(sDel.length/2) ; i++){
    temp =sDel[i] ;
    sDel[i] = sDel[j] ;
    sDel[j] = temp;
    j–;
    }

    for(int k=0;k<sDel.length;k++){
    System.out.println(sDel[k]);
    }
    }

  • Samir Vasani

    String s=”my name is ab be fh”,temp;
    String[] sDel=s.split(” “);
    int j= sDel.length-1;
    for(int i=0 ; i<(sDel.length/2) ; i++){
    temp =sDel[i] ;
    sDel[i] = sDel[j] ;
    sDel[j] = temp;
    j–;
    }

    for(int k=0;k<sDel.length;k++){
    System.out.println(sDel[k]);
    }

  • Akash Chaturvedi

    the sky is not always blue 😀

  • Guest

    In place? Without allocating extra space?

  • stefan

    // 4 line of code not 14
    public String reverseWordsInString(String str){

    String[] arr = str.split(” “); // the sky is blue
    String newArr = arr[3] + ” ” + arr[2] + ” ” + arr[0] +” “+ arr[1] ;
    return newArr ;
    }