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

34 thoughts on “LeetCode – Reverse Words in a String (Java)”

  1. val mySentence = “the sky is blue”.split(” “).reverse
    mySentence: Array[String] = Array(blue, is, sky, the)

    scala> mySentence.mkString(” “)
    res24: String = blue is sky the


  2. public static String reverseWords(String s) {
    Stack stck = new Stack();
    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("") ) { // fails if there are extra spaces between words
    if( i != 0)// don't append if it is the last word
    sb.append(arr[i]).append(" ");
    else
    sb.append(arr[i]);
    //}
    }
    //return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    return sb.toString();
    }

  3. Here’s the most simple way to achieve it:

    public class testString {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner s=new Scanner(System.in);

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

    String ss=s.nextLine();

    String sb[]= ss.split(” “);
    for(int i=sb.length-1;i>=0;i–)
    System.out.println(sb[i]);
    }

    }

    Input: Hello World
    OutPut: World Hello


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

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

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

    }

    }

    }

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

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

    }

    }

  9. 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

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

  11. reverseWord(String s){

    index = s.indexOf(” “);

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

    }

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

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

    }

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

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

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

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

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

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

    }

    }

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

    }

    }

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

    }

    }

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

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

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

  24. 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?

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

Leave a Comment