LeetCode – Reverse Words in a String (Java)

Given an input string, reverse the string word by word.

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

Java Solution

This problem is pretty straightforward. We first split the string to words array, and then iterate through the array and add each element to a new string. Note: StringBuilder should be used to avoid creating too many Strings. If the string is very long, using String is not scalable since String is immutable and too many objects will be created and garbage collected.

class Solution {
	public String reverseWords(String s) {
		if (s == null || s.length() == 0) {
			return "";
		}
 
		// split to words by space
		String[] arr = s.split(" ");
		StringBuilder sb = new StringBuilder();
		for (int i = arr.length - 1; i >= 0; --i) {
			if (!arr[i].equals("")) {
				sb.append(arr[i]).append(" ");
			}
		}
		return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
	}
}
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>

  1. Taras on 2014-6-24

    Wrong, this is required to be done in place – reverse the whole thing, then reverse individual words

  2. Cheng on 2014-7-23

    Hi, in your for loop if (!arr[i].equals(“”)) , why you judge “” instead of ” “? Isn’t that it should check if a string in the array contains spaces?

  3. Guest on 2014-9-28

    public static String reverseWords2(String s)
    {
    String[] tab = s.split(” “);
    String temp = “”;
    for(int i = 0; i<tab.length/2 ; i++)
    {
    temp = tab[i];
    tab[i] = tab[(tab.length-1)-i];
    tab[(tab.length-1)-i] = temp;
    }
    return Arrays.toString(tab);
    }

  4. Guest on 2014-9-28

    public static String reverseWords2(String s)
    {
    String[] tab = s.split(” “);
    String temp = “”;
    for(int i = 0; i<tab.length/2 ; i++)
    {
    temp = tab[i];
    tab[i] = tab[(tab.length-1)-i];
    tab[(tab.length-1)-i] = temp;
    }

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < tab.length; i++)
    {
    result.append(tab[i]).append(" ");
    }
    return result.toString();
    }

  5. Farah El Uasghiri on 2014-9-28

    public static String reverseWords2(String s)
    {
    String[] tab = s.split(” “);
    String temp = “”;
    for(int i = 0; i<tab.length/2 ; i++)
    {
    temp = tab[i];
    tab[i] = tab[(tab.length-1)-i];
    tab[(tab.length-1)-i] = temp;
    }
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < tab.length; i++)
    {
    result.append(tab[i]).append(" ");
    }
    return result.toString();
    }

  6. ramesh on 2014-10-16

    package com.exam;

    import java.util.*;

    public class MyComparator{

    public String comp(String s){

    char []ch=s.toCharArray();

    StringBuilder sb=new StringBuilder();

    for(int i=ch.length-1;i>=0;i–){

    sb.append(ch[i]);

    }

    String m=sb.toString();

    return m;

    }

    public static void main(String args[]){

    String s=(“ramesh”);

    MyComparator mc=new MyComparator();

    String ss=mc.comp(s);

    System.out.println(ss);

    }

    }

  7. muralikrishna Adusumalli on 2014-12-5

    import java.util.*;

    class Demo

    {

    public static void main(String args[])

    {

    Scanner s=new Scanner(System.in);

    System.out.println(“Enter any String:”);

    String ss=s.nextLine();

    String sb= new StringBuffer(ss).reverse().toString();

    System.out.println(“before reverse:” + ss);

    System.out.println(“after reverse:” + sb);

    }

    }

  8. kiran on 2014-12-5

    import java.util.*;

    class Demo

    {

    public static void main(String args[])

    {

    Scanner s=new Scanner(System.in);

    System.out.println(“Enter any String:”);

    String ss=s.nextLine();

    String sb= new StringBuffer(ss).reverse().toString();

    System.out.println(“before reverse:” + ss);

    System.out.println(“after reverse:” + sb);

    }

    }

  9. on_fla on 2015-2-9

    One can also use ArrayDeque instead String[], which will much more flexible since it provides FirstAdd(), LastAdd(), LastRemove() and FirstRemove() methods.

  10. MJCS on 2015-2-10

    ss = “Hello World”
    sb = “dlroW olleH”

    Requirement specification of this program:
    ss =”Hello World”
    sb = “World Hello”

  11. MJCS on 2015-2-10

    public String reverseStringEffective(String input) {

    StringBuilder sb= new StringBuilder();

    if (input != null || input.length() != 0) {

    String[] reverse = input.split(” “);

    for (int i = reverse.length – 1; i >= 0; i–) {

    sb.append(reverse[i]);

    if (i > 0) {

    sb.append(” “);

    }

    }

    }return sb.toString();

  12. Steve on 2015-2-23

    Would this solution not work?

    public String reverseWordsInStringProblem(String inputData) {
    StringBuffer result = new StringBuffer(“”);
    String[] parts = inputData.split(” “);
    for (int i = parts.length – 1; i >= 0; i–) {
    result.append(parts[i]).append(” “);
    }
    return result.toString();
    }

  13. RK on 2015-2-25

    String in Java is immutable, you know that right?

  14. Tiago Pinho on 2015-2-28

    This should work to:

    public static String reverseString(String input){
    StringBuffer result = new StringBuffer();
    StringTokenizer tokens = new StringTokenizer(input,” “);

    while(tokens.hasMoreElements()){
    result.insert(0, tokens.nextToken() + ” “);
    }

    return result.toString().trim();

    }

  15. Souraf khan on 2015-3-4

    You give me a very simple ans thanks

  16. Henrik on 2015-3-8

    This is horrible.

    private static String reverse(String s)
    {
    String[] tmp = s.split(” “);
    s = “”;
    for(int i=0; i<tmp.length; i++)
    s = s+tmp[tmp.length-i-1]+" ";
    return s.trim();
    }

  17. henrik on 2015-3-8

    And horrible formatting (skills)

  18. Jared Burrows on 2015-3-10

    This is not the same.

  19. varun on 2015-4-14

    reverseWord(String s){

    index = s.indexOf(” “);

    return index == -1?s : reverseWord(s.substring(index+1)) + ” “+s.substring(0,index);

    }

  20. Taoufik Bdiri on 2015-4-17

    Here a solution using trim() and replaceAll()

    public String reverseWords(String s) {
    StringBuilder result = new StringBuilder();
    s = s.trim().replaceAll(” +”, ” “);
    String[] arr = s.split(” “);
    System.out.println(arr.length);
    for (int i = 0; i < arr.length; i++) result.append(arr[arr.length – i – 1]).append(" ");
    return (result.toString()).substring(0, result.length() – 1);
    }

  21. daksh on 2015-6-4

    public static void main(String[] args) {

    String s=”Hello world how’s it going”;

    String[] s1=s.split(” “);

    StringBuffer reverse=new StringBuffer(” “);

    for(int i=(s1.length)-1;i>=0;i–){

    reverse.append(s1[i]);

    reverse.append(” “);

    }

    System.out.println(reverse);

    }

    much easier

  22. Sushant Raj on 2015-6-17

    before reverse:this is band
    after reverse:dnab si siht

  23. sonia on 2015-7-15

    Hi Guys , here in above solution they are using string builder class …what if we are asked to print without using any additional java class object…below is the simple solution :-

    public void word_rev(String str)

    {

    if(str.length()==0)

    return ;

    int k = str.length()-1 ;

    int n = k ;

    while(n>=0)

    {

    while(str.charAt(k)!=’ ‘)

    {

    if(k==0)

    break ;

    k– ;

    }

    if(k==0)

    {

    System.out.print(str.substring(k , n+1));

    break ;

    }

    else

    {

    System.out.print(str.substring(k+1 , n+1));

    System.out.print(” “);

    }

    n = k– ;

    }

    }

  24. Bhavani on 2015-7-30

    String str=”this is a line”;
    String str1[]=str.split(” “);
    String finalstr=” “;
    for(int i=str1.length-1;i>=0;–i)
    {
    finalstr+=str1[i]+” “;
    }
    System.out.prntln(finalstr);

  25. Dolly Agarwal on 2015-8-6

    public class Testcase {

    public static void main(String[] args) {

    String t = “my name is dolly”;

    String c[] = t.split(” “);

    //System.out.println(c.length);

    //System.out.println(c[0] + c[1] + c[2]);

    for(int i =0;i=1;j–){

    System.out.print(c[i].charAt(j-1));

    }

    System.out.print(” “);

    }

    }

    }

  26. Renzo on 2016-2-18
  27. Onkar on 2016-3-6

    private static void reverse_words(String input) {

    int i;
    System.out.println(“Input is “+input);
    StringBuilder sb = new StringBuilder();
    String[] temp = input.split(” “);

    for (i = temp.length – 1 ; i>= 0; i–)
    {
    sb.append(temp[i]);
    sb.append(” “);
    }
    System.out.println(“Reversed string is “+sb);
    }

  28. Melad on 2016-4-4


    public static void main(String[] args) {
    String str = "my name is melad";
    Stack stack = new Stack();

    String[] strArray = str.split(" ");

    for (String s : strArray) {
    stack.push(s);
    }

    StringBuilder sb = new StringBuilder();
    while (!stack.empty()) {
    sb.append(stack.pop()).append(" ");
    }

    System.out.println(sb);
    }

  29. melad on 2016-4-4

    using stack

  30. STM on 2016-10-3

    Can someone tell me what will be the complexity of this?

Leave a comment

*