Reverse Words in a String. Please help!!


  • 0
    G

    Please help me out on this question. When I run my code, it always returns me the error from leetcode compiler:

    Submission Result: Runtime Error
    Runtime Error Message: Line 19: java.lang.ArrayIndexOutOfBoundsException: -1
    Last executed input: ""

    But the problem is that I can complile it on my computer with no problem.

    Coding Problem:

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

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

    My code:

    import java.util.*;
    import java.io.*;
    class Solution 
    {
    	public static void main(String[] args) 
    	{
    		System.out.println(reverseWords("the sky is blue"));
    	}
    	public static String reverseWords(String s) {
    		StringTokenizer st=new StringTokenizer(s," ");
    		int count=st.countTokens();
    	    String array[]=new String[count];
    		int i=0;
    		while(st.hasMoreTokens())
    		{
    			array[i]=st.nextToken();
    			i=i+1;
    		}
    		String str=array[array.length-1];
    		for(int x=array.length-2;x>=0;x--)
    		{
    			str=str+" "+array[x];
    		}
    		return str;
    	}
    }

  • 0
    G

    I modified the code and it passed the compilation. But I still do not understand what was wrong with my previous code.

    The code that works:

    import java.util.*;
    import java.io.*;
    class Solution 
    {
        public static void main(String[] args) 
        {
            System.out.println(reverseWords("the sky is blue"));
        }
        public static String reverseWords(String s) {
            StringTokenizer st=new StringTokenizer(s," ");
            int count=st.countTokens();
            String array[]=new String[count];
            String str=" ";
            int i=0;
            while(st.hasMoreTokens())
            {
                array[i]=st.nextToken();
                i=i+1;
            }
            for(int x=array.length-1;x>=0;x--)
            {
                str=str+" "+array[x];
            }
            String result=str.trim();
            return result;
        }
    }

  • 0
    W

    if the string is an empty string, the array var's length is 0. So String str=array[array.length-1]; is wrong.


  • 0
    G

    Thanks for your reply! But my understanding is that array has already been assigned elements by while(){} block before it. So, array should not be empty.


  • 0
    J

    My method is accepted.I hope it can help you.

    public static String reverseWords(String s) {
    
    	StringBuffer str = new StringBuffer();
    
    	String[] words = s.split(" ");
    
    	for (int i = words.length-1; i >=0; i--) {
    
    		if(!"".equals(words[i])){
    
    			str.append(words[i]+" ");
    
    		}
    
    	}
    
    	String result = str.toString();
    
    	return result.endsWith(" ")?result.substring(0, result.lastIndexOf(" ")):result;
    
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.