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>
  • STM

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

  • melad

    using stack

  • Melad


    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);
    }

  • Onkar

    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);
    }

  • Renzo
  • Dolly Agarwal

    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(” “);

    }

    }

    }

  • Bhavani

    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);

  • sonia

    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– ;

    }

    }

  • Sushant Raj

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

  • daksh

    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

  • 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);
    }

  • reverseWord(String s){

    index = s.indexOf(” “);

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

    }

  • This is not the same.

  • henrik

    And horrible formatting (skills)

  • Henrik

    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();
    }

  • Souraf khan

    You give me a very simple ans thanks

  • Tiago Pinho

    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();

    }

  • RK

    String in Java is immutable, you know that right?

  • Steve

    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();
    }

  • MJCS

    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();

  • MJCS

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

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

  • on_fla

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

  • kiran

    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);

    }

    }

  • muralikrishna Adusumalli

    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);

    }

    }

  • ramesh

    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);

    }

    }

  • Farah El Uasghiri

    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();
    }

  • Guest

    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();
    }

  • Guest

    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);
    }

  • Cheng

    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?

  • Taras

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