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>

  1. stefan on 2016-6-16

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

  2. Guest on 2016-6-21

    In place? Without allocating extra space?

  3. Akash Chaturvedi on 2016-8-1

    the sky is not always blue 😀

  4. Samir Vasani on 2016-8-3

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

  5. Samir Vasani on 2016-8-3

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

  6. Amit Chaudhary on 2016-8-12

    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.

  7. Raghu Mahajan on 2016-8-14

    we cant use any extra space

  8. Raghu Mahajan on 2016-8-14

    cant use extra space

  9. Christian on 2016-8-21

    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.

  10. omar farag on 2016-8-22

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

  11. Amit Chaudhary on 2016-8-24

    This works.

  12. Noe Alejandro Perez Domínguez on 2016-9-12

    Possible one liner in Scala


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

  13. NightCoder on 2016-9-15

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

  14. Satyendra Talatam on 2016-9-21

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

  15. Avinash Ujjwal on 2016-9-26

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

  16. bpgen on 2016-9-28

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

  17. sewa on 2016-10-2

    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.

  18. Dnyanada Pramod Arjunwadkar on 2016-10-10


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

  19. Huy on 2016-10-23

    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.

  20. karthik339 on 2016-11-4

    I liked this implementaion. Fast and efficinent.

  21. Bukary Kandeh on 2017-1-29


    public static void ReverseString(String s) {
    String[] split = s.split(" ");
    StringBuilder sb = new StringBuilder();

    for (int i = split.length - 1; i >= 0; i--) {
    sb.append(split[i] + " ");
    }
    System.out.println(sb.setLength(sb.length() - 1).toString());
    }

  22. Brikesh Kumar on 2017-2-6


    public class Program
    {
    public static void Main(string[] args)
    {
    //Your code goes here
    var input = "Hello";
    Console.WriteLine(string.Format("Before reversing: - {0}",input));
    var inPutArray = input.ToCharArray();
    //var reversed = new StringBuilder();
    //Reverse the string
    for(int i= 0, j = inPutArray.Length - 1; i <= j;i++,j--){

    var temp = inPutArray[i];
    inPutArray[i] = inPutArray[j];
    inPutArray[j] = temp;
    }
    Console.WriteLine(string.Format("After reversing: - {0}",new String(inPutArray)));
    }
    }

  23. Carlos Pérez on 2017-2-9

    funny, I had done something really similar:
    public static String reverseWords(String str) {
    StringBuilder sb = new StringBuilder();
    int limit = str.length();
    //from last to first
    for (int i = str.length() – 1; i > 0; i–) {
    if (str.charAt(i) == ‘ ‘) {
    sb.append(str.substring(i + 1, limit)).append(‘ ‘);
    limit = i;
    }
    }
    sb.append(str.substring(0, limit));

    return sb.toString();
    }

  24. Carlos Hernandez on 2017-3-30

    how about trimming the SB instead of setting the length?

  25. Bukary Kandeh on 2017-3-31

    Trimming will get rid of the space between the words, that’s NOT what we want to do. I append space between the words so “sb.length() – 1” just deletes the last space.

    Example: String s = “the sky is blue”;

    *If you apply the TRIM you’ll get the following: “blueisskythe”.
    *My application WITHOUT the “sb.length() – 1”: “blue is sky the ”
    *My application WITH the “sb.length() – 1”: “blue is sky the”

    setLength() is the most efficient way to get rid of the final space. Basically, it alters the count and overwrites the value we don’t want with a zero byte.

  26. Sagarika Dusane on 2017-7-26

    String word = “The sky is Blue”;
    List wordList = Arrays.asList(word.split(” “));
    Collections.reverse(wordList);
    word = String.join(” “, (CharSequence[]) wordList.toArray());

    System.out.println(word);
    }

  27. tan nguyen on 2017-8-18

    public static String reverse(String s) {
    String tmp = new StringBuilder(s).reverse().toString();
    char[] in = tmp.toCharArray();
    int j = 0;
    for (int i = 0; i < in.length; i++) {
    if (in[i] == ' ') {
    reverseChar(in, j, i – 1);
    j = i + 1;
    }
    if (i == in.length-1)
    {
    reverseChar(in, j, i);
    }
    }
    StringBuilder sb = new StringBuilder(in.length);
    sb.append(in);

    return sb.toString();
    }

    public static void reverseChar(char[] input, int i, int j) {
    int b = j;
    for (int a = i; a <= b; a++) {
    char tmp = input[a];
    input[a] = input[b];
    input[b] = tmp;
    b–;
    }
    //final StringBuilder sb = new StringBuilder(input.length);
    //sb.append(input);

    // System.out.print(sb.toString());
    }

  28. vijay on 2017-9-13

    package java8fileread;

    public class Rev {

    public static void main(String[] args) {
    String s = “hello”;
    String rev = reverse(s.toCharArray(), ‘ ‘, s.length());
    System.out.println(rev);
    }

    static String rev= “”;
    private static String reverse(char[] charArray, char e, int length) {
    if(length != 0)
    {
    if(e != ‘ ‘) rev += e;
    reverse(charArray, charArray[–length], length) ;
    }
    return rev + charArray[0];
    }
    }

  29. Ayman Ali on 2017-10-30

    var input = “ayman ali”;
    input = ” ” + input;
    var arr = input.ToCharArray();
    var output = string.Empty;
    var b = 0;
    var e = arr.Length;
    for (int p = arr.Length – 1; p >= 0; p–)
    {
    if (arr[p] == ‘ ‘ )// little off beginning of word
    {
    b = p + 1;
    output += input.Substring(b, e – b) + ” “;
    e = p ;

    }
    }
    Console.WriteLine(output.TrimEnd(‘ ‘));
    Console.ReadLine();

Leave a comment

*